Skip to content
Advertisement

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" . "rn" .
            "CC: ***********@gmail.com";

        mail($to, $subject, $txt, $headers);
    }
} else {
    echo "0 results";
}
$conn->close();

Advertisement

Answer

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 . "rn";
    }

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

    mail($to, $subject, $txt, $headers);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement