tags:

views:

57

answers:

5

Say, I have a whole lot of book titles in the database (more than 500000) and someday I want to add another title in the database, how would I check whether the database already contains this title or not? How would I do it in php?

+2  A: 

Something like SELECT 1 FROM table WHERE title = '' springs to mind, with an index on title ofcourse :)

From PHP:

$query = mysql_query("SELECT 1 FROM table WHERE title = '%s'", 
    mysql_real_escape_string($title));
$result = mysql_query($query);
if(mysql_num_rows($result)){
    echo 'The title exists in the database';
}
WoLpH
the problem with this is that someone else could insert that record after you have checked with "select" and before you do your "insert". The most reliable method is to "insert" and catch a "duplicate key" error - assuming you have an appropriate unique or primary key defined (which you should).
Martin
Correct, how you would implement this would depend on the use case ofcourse. An `INSERT IGNORE` or `INSERT ON DUPLICATE KEY UPDATE` might be a better solution.
WoLpH
A: 

or you could execute the actual insert statements and wait for the results. if the row you are inserting is already in the database, assuming that you define some sort of a primary key in the table, it will post an error... duplicate entry not allowed blah... and you can "catch" it... just a thought!

ultrajohn
+1  A: 

If you really want a title to be unique, best to express that as a unique constraint on the title column.

duffymo
A: 
insert ignore into

It inserts if not exists, otherwise no op. [assuming title has unique constraint]

Fakrudeen