Skip to content
PHP Logo

How can the PHP code be modified to properly retrieve data from the database for sending emails?

The PHP code needs to establish a connection to the database, retrieve the necessary data for sending emails, and then loop through the results to send emails to each recipient. The code should use proper error handling to catch any potential issues with the database connection or query execution.

php
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the database for sending emails
$sql = "SELECT email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Loop through the results and send emails
    while($row = $result->fetch_assoc()) {
        $to = $row['email'];
        $subject = "Test Email";
        $message = "This is a test email.";
        $headers = "From: your@example.com";

        mail($to, $subject, $message, $headers);
    }
} else {
    echo "0 results";
}

$conn->close();
?>