Jump to content

Mysql : IF NOT EXISTS


remenissions

Recommended Posts

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 */

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.