Note that there are some explanatory texts on larger screens.

plurals
  1. POShould I check a unique constraint with php?
    primarykey
    data
    text
    <p>Maybe this question has already been asked, but I don't really know how to search for it:</p> <p>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.</p> <p>I access the table with php.</p> <p>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.</p> <p>What I want to do is to show an error in the html-input-field: "Customer-Name already taken" when this happens.</p> <p>My question is how I should do this.</p> <p>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?</p> <p>What is better practice? Making a further sql-statement, or catching and analyzing error-codes.</p> <p><strong>EDIT:</strong> 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.</p> <p><strong>EDIT2:</strong> 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.</p> <p>This is everything I get from the exception:</p> <pre><code>["23505",7,"FEHLER: doppelter Schlüsselwert verletzt Unique-Constraint &lt;customers_name_unique&gt;\nDETAIL: Schlüssel &lt;(name)=(test)&gt; existiert bereits."] </code></pre> <p>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).</p> <p>But as you can also see, the message is in german, so the output depends on the system / might be able to change.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload