Error Handling for Duplicate Entries in PHP
When working with MySQL databases in PHP, it's common to encounter duplicate entry errors. By default, MySQL will return an error message like "Duplicate entry 'entered value' for key 1" when a user attempts to input a value that already exists in the table.
To improve user experience, you might want to handle this error and provide a more user-friendly message. Here's how to turn a specific MySQL error into a PHP message:
Here's an example of how to implement this error handling:
mysqli_query('INSERT INTO ...'); if (mysqli_errno() == 1062) { print 'The entered value already exists. Please enter a different value.'; }
Note on Coding Style:
It's good practice to avoid using magic numbers in code. Instead, assign the known error code to a constant (e.g., MYSQLI_CODE_DUPLICATE_KEY) to make your code more readable and maintainable.
The above is the detailed content of How to Handle Duplicate Entries in PHP MySQL: A User-Friendly Approach?. For more information, please follow other related articles on the PHP Chinese website!