[thelist] insert if select fails to find element

Mark Rees mrees at itsagoodprice.com
Thu Nov 17 03:06:27 CST 2005


> // $dictionary has 100,000 elements
> // open link
> while($word = array_pop($dictionary)){
>     // check we dont have this word already in our store
>     $query_string = "SELECT word FROM word_list WHERE word = '$word'";
>     $result = mysql_query ($query_string) or die(mysql_error());
>
>     if(!mysql_num_rows($result)){
>         $query = "INSERT into word_list(word) VALUES ('$word')";
>         mysql_query($query) or die(mysql_error()); ;
>         $counter++;
>     }
> }
> // close link
>
> is there a way of putting all the work on the sql - something like
>
> ""INSERT into word_list(word) VALUES ('$word')" IF ('$word') NOT EXISTS";
>

This is roughly the sql syntax you are looking for. I don't know whether it
will work in mysql though - a quick look at the manual didn't turn anything
up, so you might as well just try it and see what happens.

IF NOT EXISTS (SELECT word FROM word_list WHERE word='$word') INSERT INTO
word_list(word) VALUES ('$word');





More information about the thelist mailing list