Reputation: 4662
how can insert a record if only a specific value doesn't exist in a field
INSERT INTO `users` (fb_id, username)
SELECT '.$id_signed_in.', '.$user_signed_in.' FROM `users`
WHERE NOT EXISTS (SELECT * FROM `users`
WHERE fb_id='.$id_signed_in.')
LIMIT 1'
this does not seem to work
Upvotes: 0
Views: 186
Reputation: 3877
Simple way:
If you want a field to be unique, set it as unique and delete duplicate entries if exists.
You can use
insert ignore into users (fb_id, username) values ('$id_signed_in','$user_signed_in')
Here you have to set fb_id as unique to prevent duplicate entries. It only inserts, if fb_id doesn't exists in the db.
Another way without using ignore, unique :
$res = mysql_query("select id from users where fb_id='$id_signed_in'");
if(!(mysql_num_rows($res)>0)){
mysql_query("insert into users (fb_id, username) values ('$id_signed_in','$user_signed_in')");
}
Upvotes: 0
Reputation: 2285
Please try this ,
INSERT INTO `users` (fb_id, username)
SELECT '.$id_signed_in.', '.$user_signed_in.' FROM `users`
WHERE fb_id NOT IN(SELECT fb_id FROM `users`
WHERE fb_id='.$id_signed_in.')
LIMIT 1'
Upvotes: 1