Maybe this question has already been asked, but I don't really know how to search for it:
I have the postgres-table "customers", and each customer has it's own unique name. In order to achieve this, I added an unique-constraint to this column.
I access the table with php.
When the user now tries to create a new customer, with a name that has already been taken, the database says "Integrity Constraint Violation", and php throws an error.
What I want to do is to show an error in the html-input-field: "Customer-Name already taken" when this happens.
My question is how I should do this.
Should I catch the PDO-Exception, check if the error-Code is "UNIQUE VIOLATION", and than display a message according to the Exception-Message, or should I check for duplicate names with an additional statement before I even try to insert a new row?
What is better practice? Making a further sql-statement, or catching and analyzing error-codes.
EDIT: I'm using transactions, and I'm catching any exception in order to rollback. The question is, if I should filter out Unique-violations so they don't lead to a rollback.
EDIT2: If I'm using the exception-method, I would have to analyse the exception-message in order to ensure that the unique-constraint really belongs to the "name"-column.
This is everything I get from the exception:
["23505",7,"FEHLER: doppelter Schlüsselwert verletzt Unique-Constraint <customers_name_unique>\nDETAIL: Schlüssel <(name)=(test)> existiert bereits."]
The only way to get information about the column is to check if "customers_name_unique" exists (it's the name of the unique-constraint).
But as you can also see, the message is in german, so the output depends on the system / might be able to change.