# php SQL INSERT INTO WHERE NOT EXISTS



## xres

Please can someone help me with an issue I am having with the INSERT INTO WHERE NOT EXISTS Function. Here is my code so far:



Code:


$query = ("INSERT INTO document_association2 (name) VALUES ('$groupname') WHERE NOT EXISTS (document_association2.name = '$groupname'");
$result = mysql_query($query)
or die("error: ".
mysql_error());

I am wishing to insert a new row into document_association2 but only if if an item in the column 'name' is not already existing.

Thank you


----------



## Redcore

Shouldn't that be a subquery? Instead of "(document_association2.name = '$groupname'")" shouldn't it be something more like "(SELECT * FROM document_association WHERE document_association2.name = '$groupname'") ?


----------



## xres

Thank you for your reply Redcore and I understand your logic behind that response. Unfortunately my query still seems to be failing using your suggestion of:



Code:


$query = ("INSERT INTO document_association2 (name) VALUES ('$groupname') WHERE NOT EXISTS (SELECT * FROM document_association2 WHERE document_association2.name = '$groupname'");
$result = mysql_query($query)
or die("error: ".
mysql_error());

Are there anyother means that I could use that will help me simply search the 'name' column, determine if the name has already been entered, then add OR update the row depending on the result. Thanks in advance


----------



## maretard

Note: The OP's question has been answered on Yahoo Answers (though apparently he has not checked yet). 

Available at: http://answers.yahoo.com/question/index?qid=20090406133733AAyLnwh

In fact, the OP has posted this on several forums (nothing wrong with that, just found it funny that the first ten results on Google for "INSERT WHERE NOT EXISTS" were the exact same question ).

To the OP: I found an excellent little blurb on codesplatter for exactly this situation. It allows you to insert a new row into a table if its key is not already present in the table, and update existing rows if the key is already present. Check it out here: http://codespatter.com/2008/04/30/swap-insert-for-update-when-key-exists/

Regards,
Alvin

PS: Btw, Redcore, sweet icon, with the reflection and whatnot. ray:


----------



## xres

Thank you all for your help. I have decided on this occasion to use a solution provided by a user of yahoo answers:



Code:


$query = mysql_query("SELECT name FROM database_table WHERE name='$groupname'");
$num_query = mysql_num_rows($query);

if($num_query == "0")**
$_insert = mysql_query("INSERT INTO databasetable_name (name) VALUES('$groupname')");
}
else{
echo "There is a group there already";
}

I think I was making my query more difficult than it needed to be.
Cheers


----------

