Home >Database >Mysql Tutorial >How to Detect and Handle Database Insertion/Update Failures due to Unique Key Constraints?
In database programming, it's common to encounter scenarios where you need to ensure data uniqueness through unique constraints. This can lead to failures during insertion or update operations when duplicate values are encountered.
Suppose you have a table with a single column named "title" that has a unique constraint applied. You insert a row with the title value "something." Now, upon attempting another insertion with the same title value, the operation will fail due to the unique key constraint.
Your goal is to detect and handle this failure. You want the database to enforce the uniqueness while your code intercepts the error code to inform the user of the duplicate title.
Today, PHP PDO is the preferred method for database interactions. To detect insertion failures caused by unique key constraints with PDO, follow these steps:
<code class="php">try { // PDO query execution goes here. } catch (\PDOException $e) { if ($e->errorInfo[1] == 1062) { // The INSERT query failed due to a key constraint violation. } }</code>
The $e->errorInfo array provides detailed information about the error, including code 1062 for unique key violations.
The above is the detailed content of How to Detect and Handle Database Insertion/Update Failures due to Unique Key Constraints?. For more information, please follow other related articles on the PHP Chinese website!