People
I am trying to use the same script for approving a contact to be added to the database, but the query will do an update if the primary key (id) is already there. So i set up a INSERT INTO …. ON DUPLICATE KEY UPDATE query, which is below:
$resultsc = mysql_query("INSERT INTO $contact (id,First,Last,Companyid,userid,Title,PrimaryPhone,SecondaryPhone,PrimaryEmail,SecondayEmail,inserted) VALUES('$id','$first','$last','$companyid','$userid','$title','$phone1','$phone2','$email1','$email2',NOW()) ON DUPLICATE KEY UPDATE (First,Last,Companyid,userid,Title,PrimaryPhone,SecondaryPhone,PrimaryEmail,SecondayEmail) VALUES ('$first','$last','$companyid','$userid','$title','$phone1','$phone2','$email1','$email2') WHERE id='$id'");
if(!$resultsc)
{
echo "<font face='Verdana' size='2' ><center>You have successfully approved this user for access to this site.</center><br><center><input type='button' value='Back' onClick='history.go(-2)'></center>"; die();
}
else
{
echo "<font face='Verdana' size='2' ><center>You have not updated this contact for this site.</center><br><center><input type='button' value='Back' onClick='history.go(-2)'></center>";
}
I am not getting any errors but the database is not updating or inserting a new record. So I checked my “$contacts” variable to ensure it is is pointing to the correct table, and it is. If i just do an insert alone then the script is working fine. But when i do this query nothing happens. I am wondering what is wrong with it or should i just have a if/else with a select checking for a existing key?
The syntax is wrong.
Note the use of the
values()function. It’s very handy in theseon dupequerys, so you don’t have to insert the field’s value twice (once in the insert part, once in the update part). MySQL will simply use the value from the insert portion again in the update. Very handy if you’re inserting ‘large’ data and don’t want to waste bandwidth on duplicate data.On a metalevel, don’t output a fixed error messages as you are while in debugging phase:
is far more useful and helpful than “oops, something didn’t work”.