remenissions Posted January 4, 2012 Share Posted January 4, 2012 Hey guys, I'm in need of a little help with sql. I'm just wanting to make sure I do this correctly. I have a mysql statement for adding contacts from request list to friends list. Before I was using two statements to check if the users already existed as friends (to prevent duplicates), but I'm wanting to use one statement. I've looked around a little and I have a few examples such as the following, but do these statements require a primary key? I haven't really looked much into what primary keys do I'd just assume its a special id for a certail row or table or something. I just want to be for certain I'm doing this correctly before I do submit it live on my server. INSERT INTO `table` (value1, value2) SELECT 'stuff for value1', 'stuff for value2' FROM `table` WHERE NOT EXISTS (SELECT * FROM `table` WHERE value1='stuff for value1' AND value2='stuff for value2') LIMIT 1 Here is what I currently have going on, though I'm not sure if "IGNORE" works w\o a primary key either and from what I've seen its not really preferred. /* Adding Contacts */ if(!empty($_POST['addPosition']) && !empty($_POST['targetId'])) { /* -Delete from requests- */ deleteContact($_POST['addPosition'], $_POST['targetId']); /* -/Delete from requests- */ /* -Insert target into friends list- */ mysql_query("INSERT IGNORE INTO Friends_List (Requester_Id, Friend_Id) VALUES ('". mysql_real_escape_string($_POST['targetId']) ."', '". mysql_real_escape_string($userId) ."')"); echo "User successfully added!"; /* -/Insert target into friends list- */ } /* /Adding Contacts */ Quote Link to comment https://forums.phpfreaks.com/topic/254316-mysql-if-not-exists/ Share on other sites More sharing options...
fenway Posted January 4, 2012 Share Posted January 4, 2012 IGNORE requires some UNIQUE key, not necessarily a primary key. Quote Link to comment https://forums.phpfreaks.com/topic/254316-mysql-if-not-exists/#findComment-1304033 Share on other sites More sharing options...
remenissions Posted January 4, 2012 Author Share Posted January 4, 2012 Thanks for your reply bud Quote Link to comment https://forums.phpfreaks.com/topic/254316-mysql-if-not-exists/#findComment-1304070 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.