PHP validation vs MySQL validation

Hey guys,

What is more efficient in this example? PHP script inputs data into MySQL database. Should I first check to see if an identical record exists (don’t want identical) with PHP by doing a SELECT statement? Or should I just set the field to be UNIQUE in MySQL and just let the user try to input identical data but fail thanks to MySQL?

I’m wondering which is more efficient. Using PHP to check via mysql_query every time seems exhaustive especially if users don’t try and input identicals. But what if I just let MySQL reject the data? Is that a performance hogger? Or is this the ideal approach?

Thanks guys!

the latter

it’s twice as efficient, as it does only one database call instead of two

As Rudy says, you can let it fail at the database.

Don’t forget, however, to catch the database’s error message so that you can tell the user why it failed.

Good point! Thanks for the reminder.

mysql err no. 1062 Message: Duplicate entry ‘%s’ for key %d

MySQL :: MySQL 5.5 Reference Manual :: C.3 Server Error Codes and Messages

Hey great info everyone - even though I know I’m a little late to the party. So far it works perfectly. What I’m trying to do is verify whether a street address has been previously inputted or not.

Checking UNIQUE works just fine when the address is all contained in one input box (on html form) and one row of the table, but I’d like to standardize it a bit more with street address, city, state, country, zip all having their own input box (on the html form).

I’m wondering what is the best practice for something like this. Would I have each html field as a populate a separate row in the table? Or could I combine all the data from the different input boxes (of the html form) and have them populate one row in the table?

Thanks in advance,
Stephen