stubarny Posted May 16, 2012 Share Posted May 16, 2012 Hello, I have the following code which is trying to insert data into a table. However, the field "website_page_name" has a unique field therefore if a value already exists the code below fails. $query="INSERT INTO website_page_names (website_page_name, website_page_name_company, website_page_name_job_specialism, website_page_name_location) VALUES ('$mysql_real_escape_string_website_page_name_with_dashes', '$mysql_real_escape_string_company_name', '$mysql_real_escape_string_job_specialism_phrase', '$mysql_real_escape_string_location')"; Please could you tell me how to check that the value for "website_page_name" has not already been entered into the table? Many thanks, Stu Quote Link to comment https://forums.phpfreaks.com/topic/262594-checking-a-value-in-a-unique-index-doesnt-exist-before-doing-insert-query/ Share on other sites More sharing options...
PravinS Posted May 16, 2012 Share Posted May 16, 2012 Before your INSERT query write a SELECT query which will check "website_page_name" in table, if SELECT query returns any result then give error message that "record already exists" else insert record in table. Also you can set UNIQUE key for "website_page_name" field of table then you will not need to write above SELECT query. Quote Link to comment https://forums.phpfreaks.com/topic/262594-checking-a-value-in-a-unique-index-doesnt-exist-before-doing-insert-query/#findComment-1345863 Share on other sites More sharing options...
Illusion Posted May 16, 2012 Share Posted May 16, 2012 if you want update the record if found one with same web page name, you can use "ON DUPLICATE KEY UPDATE " as weg_page_name has UNIQUE key Quote Link to comment https://forums.phpfreaks.com/topic/262594-checking-a-value-in-a-unique-index-doesnt-exist-before-doing-insert-query/#findComment-1345866 Share on other sites More sharing options...
PFMaBiSmAd Posted May 16, 2012 Share Posted May 16, 2012 Here are two ways to handle the duplicate - 1) Leave the query as is and then specifically test the error number that is returned to see if the query produced a duplicate key error. You will need to experiment to find that error number, I think it is 1062, but don't take my word for that. 2) Add the IGNORE keyword to your query statement. If a duplicate key error does occur when the query runs, the error condition won't be returned. You can use mysql_affected_rows to check if the row was inserted or not. Quote Link to comment https://forums.phpfreaks.com/topic/262594-checking-a-value-in-a-unique-index-doesnt-exist-before-doing-insert-query/#findComment-1345915 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.