e1seix Posted December 23, 2009 Share Posted December 23, 2009 Quick one guys. I'm running an INSERT INTO script and what I'm trying to do is get it to check if what it's trying to insert is already present in my database and therefore skip it. mysql_query("INSERT INTO names ( firstname ) VALUES ( 'Bob')") or die(mysql_error()); Running a for loop and basically, if Bob is already present in database under the firstname column, sjip it - how do i put that into the WHERE clause. Many thanks and happy hols Quote Link to comment https://forums.phpfreaks.com/topic/186185-if-it-exists/ Share on other sites More sharing options...
premiso Posted December 23, 2009 Share Posted December 23, 2009 You can make the field UNIQUE which would not allow it to be inserted. The only other way that I know of would be to do a SELECT query before the insert to test if that name is present in the database. Quote Link to comment https://forums.phpfreaks.com/topic/186185-if-it-exists/#findComment-983311 Share on other sites More sharing options...
trq Posted December 23, 2009 Share Posted December 23, 2009 Or, use INSERT.... ON DUPLICATE. $sql = " INSERT INTO names (firstname) VALUES ('Bob') ON DUPLICATE KEY UPDATE firstname = 'Bob'; "; The 'firstname' field would still however need to have a unique constraint. See here for more details. Quote Link to comment https://forums.phpfreaks.com/topic/186185-if-it-exists/#findComment-983317 Share on other sites More sharing options...
Daniel0 Posted December 23, 2009 Share Posted December 23, 2009 You can also use REPLACE INTO ... or INSERT IGNORE INTO .... I'd use thorpe's suggestion, though I might do ON DUPLICATE KEY UPDATE firstname = firstname so it can optimize the update statement away. Quote Link to comment https://forums.phpfreaks.com/topic/186185-if-it-exists/#findComment-983347 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.