I am trying to insert contacts into database but does not want to duplicate already existing contact.
Not sure INSERT has WHERE CLAUSE.
Any ideas?
Perhaps you want to do an "upsert"? That means that you try to do an INSERT, and if the record already exists, you do an UPDATE instead.
To do that, first use a SELECT to see if the record already exists. If the contact isn't in the database, do an INSERT. If the contact is already in the database, do an UPDATE.
Another option is:
//Insert INTO contact database
$user_id = userid;
$sql_insert = "INSERT into `jt_members_external_contacts`
(`j_user_id`,`contact_email`,`firstname`)
SELECT '$user_id','$email','$name'
FROM `jt_members_external_contacts`
WHERE j_user_id !=$user_id AND contact_email != $email;";
You could use a stored procedure that checks if the record first exists before doing an insert. If the record exists, the stored procedure would do an update.
The advantage of using a stored procedure instead of a select followed by an update is you only hit the database server once instead of twice.
You can use:
INSERT ... ON DUPLICATE KEY UPDATE
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html