stevil Posted March 9, 2008 Share Posted March 9, 2008 What I'm looking for is the fastest way to check if a record exisits, if it does I need to get it's ID, if not I need to create the record and then get it's ID. I guess the best way to explain it is to show you. if($BookCHK = mysql_fetch_assoc(mysql_query("SELECT book_id FROM books WHERE book_title = '$BookName';"))){ $BookID = $BookCHK['book_id']; }else{ mysql_query("INSERT INTO books(book_title) VALUES('$BookName');"); $BookID = mysql_insert_id(); } The above code does work, but I think there is probably a better way to acheive this. I originally thought a " ON DUPLICATE KEY UPDATE" in myself might work, then I realised the that "book_title" isn't a key so it just doesn't work =( Surely there is something which is better than this to achieve these results. The server that is running this script will be running about 300,000,000 queries a day, so if I could cut this down to just one query and lessen the checks it would be huge load off the server's back (pun intended). Anyone have any ideas? Any help would be greatly appreciated! Quote Link to comment Share on other sites More sharing options...
stevil Posted March 9, 2008 Author Share Posted March 9, 2008 Just a note as to ON DUPLICATE UPDATE :- mysql_query("INSERT INTO books(book_title) VALUES('$BookName') ON DUPLICATE KEY UPDATE 1=1"); $BookID = mysql_insert_id()-(mysql_affected_rows()>1?mysql_affected_rows:0); This will work, but again we have an update being run which isn't needed. Again I want to speed it up as much as possible, so would rather not have the update. This does return the correct ID and more than likely faster than my previous method. But I'm looking for the fastest possible method. I'm sure it's something REALLY simple, but I've just not had to do it before so never had to worry about it. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.