I'm writting a HTML form for newsletter subscribers. So far the form ignores duplicates entries by making the subscriber_email field unique in the mysql table and using:
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
I'm trying to improve the form so it updates the other fields when the email already exists in the table, and if the email does not exists then it inserts a new record. For that I'm doing this (so far it works but I feel it's not the proper way to do it):
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Try update into DB---------------------------------------------------------//
$sqlUpdate =
"UPDATE newsletter_subscriber_popup
SET subscriber_name = '$subscriber_name'
WHERE subscriber_email = '$subscriber_email'";
if(!mysql_query($sqlUpdate)){
//Insert into DB--------------------------------------------------------//
$sqlInsert =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')";
if(!mysql_query($sqlInsert)){
die('Error: ' .mysql_error());
}
}
The scripts works when the subscriber_email exists and it updates the other fields but it fails when it should insert a new record.
EDIT----------------------------
ON DUPLICATED KEY UPDATE is what I was looking for. The script now updates the other fields when the subscriber_email already exists, and insert a new record when the the subscriber_email does not exists.
//HTML form variables----------------------------------------------------//
$subscriber_name = mysql_real_escape_string($_POST['subscriber_name']);
$subscriber_email = mysql_real_escape_string($_POST['subscriber_email']);
//Insert into DB--------------------------------------------------------//
$sqlName =
"INSERT IGNORE INTO newsletter_subscriber_popup (subscriber_name, subscriber_email)
VALUES ('$subscriber_name', '$subscriber_email')
ON DUPLICATE KEY UPDATE subscriber_name = '$subscriber_name'";
if(!mysql_query($sqlName)){
die('Error: ' .mysql_error());
}
Note: Thanks for all the advices about sql injection but the question wasn't about security.