Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
116 views
in Technique[技术] by (71.8m points)

php - I want to send the filtered data to my mail from the Database

I have written the code for Filter the data from Database and send the result via mail. Its sending the mail, but its sending separate mails for each row displaying in the result. I want the result in a single mail. I have share the code iam using now.

<?php

$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DBNAME";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT user_id, user_phone, user_email FROM registers WHERE status='0'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = $result->fetch_assoc()) {
        $rows = "id: " . $row["user_id"] . " - Name: " . $row["user_phone"] . " " . $row["user_email"];
        echo "$rows";


        $to = "******@gmail.com";
        $subject = "My subject";
        $txt = "$rows";
        $headers = "From: admin@******.com" . "
" .
            "CC: ***********@gmail.com";

        mail($to, $subject, $txt, $headers);
    }
} else {
    echo "0 results";
}
$conn->close();
question from:https://stackoverflow.com/questions/65907046/i-want-to-send-the-filtered-data-to-my-mail-from-the-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you can just use .= to concatenate onto the txt variable, and then move the mail stuff outside of the loop.

    $txt = '';
    while ($row = $result->fetch_assoc()) {
        $rows = "id: " . $row["user_id"] . " - Name: " . $row["user_phone"] . " " . $row["user_email"];
        echo "$rows";
        
        $txt .= $rows . "
";
    }

    $to = "******@gmail.com";
    $subject = "My subject";
    $headers = "From: admin@******.com" . "
" .
        "CC: ***********@gmail.com";

    mail($to, $subject, $txt, $headers);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...