I have a PHP form that enters data into my MySQL database. My primary key is one of the user-entered values. When the user enters a value that already exists in the table, the MySQL error "Duplicate entry ‘entered value’ for key 1" is returned.
Instead of that error, I would like to alert the user that they need to enter a different value. Just an echoed message or something.
How to turn a specific MySQL error into a PHP message?
To check for this specific error, you need to find the error code. It is
1062for duplicate key. Then use the result fromerrno()to compare with:A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (
1062) to a constant (e.g.MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in theifstatement is still readable in a few months when the meaning of1062has faded from memory 🙂