How can one ensure that duplicate email addresses are not added to a database when automating newsletter sign-ups?
When automating newsletter sign-ups, one way to ensure that duplicate email addresses are not added to a database is to first check if the email address already exists in the database before inserting it. This can be done by querying the database to see if the email address is already present. If it is, then do not insert it again. If it is not, then go ahead and insert the new email address.
// Assuming $email contains the email address to be added
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "newsletter";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check if email address already exists
$sql = "SELECT * FROM subscribers WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "Email address already exists in database";
} else {
// Insert email address into database
$sql = "INSERT INTO subscribers (email) VALUES ('$email')";
if ($conn->query($sql) === TRUE) {
echo "New email address added successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close database connection
$conn->close();