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
https://forums.phpfreaks.com/topic/254316-mysql-if-not-exists/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.