What are the best practices for accessing a database in PHP to retrieve email addresses for sending form data to multiple recipients?

When retrieving email addresses from a database in PHP to send form data to multiple recipients, it is best practice to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to validate the email addresses before sending the form data to ensure they are in the correct format. Finally, consider using a mailing library like PHPMailer to handle the email sending process efficiently.

// Connect 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 email addresses from the database
$sql = "SELECT email FROM recipients";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($email);

$recipients = array();
while ($stmt->fetch()) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $recipients[] = $email;
    }
}

$stmt->close();
$conn->close();

// Send form data to multiple recipients using PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'smtp.example.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'your@example.com';
    $mail->Password = 'yourpassword';
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('from@example.com', 'Your Name');
    foreach ($recipients as $recipient) {
        $mail->addAddress($recipient);
    }

    $mail->isHTML(true);
    $mail->Subject = 'Subject';
    $mail->Body = 'Email body';

    $mail->send();
    echo 'Email sent successfully';
} catch (Exception $e) {
    echo 'Email could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}