Jump to content

Checking a value in a unique index doesn't exist before doing INSERT query


stubarny

Recommended Posts

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

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.