What are common pitfalls when using PHP Mailer to send emails with data from a MySQL table?
Common pitfalls when using PHP Mailer to send emails with data from a MySQL table include not properly sanitizing user input, not handling errors effectively, and not securely connecting to the database. To solve these issues, make sure to sanitize user input to prevent SQL injection attacks, implement error handling to catch any issues with sending emails, and use secure database connection methods to protect sensitive information.
// Example code snippet to securely connect to MySQL database and send emails using PHP Mailer
// Database connection
$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);
}
// Query MySQL table for data
$sql = "SELECT email, name FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
require 'PHPMailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
while($row = $result->fetch_assoc()) {
$mail->addAddress($row['email'], $row['name']);
$mail->Subject = 'Subject';
$mail->Body = 'Email content';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
$mail->clearAddresses();
}
} else {
echo "0 results";
}
$conn->close();