views:

47

answers:

3

I have a PHP form which 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. I guess my question comes down to: how to turn a specific MySQL error into a PHP message Thanks

edit: nickf's answer below is nice, but is there any way to discern between specific errors?

+1  A: 

With mysql_error() function http://php.net/manual/en/function.mysql-error.php

Codler
this just turns on error reporting, as far as i can tell. thanks anyway.
RobHardgood
+2  A: 

You can check the return value from mysql_query when you do the insert.

$result = mysql_query("INSERT INTO mytable VALUES ('dupe')");

if (!$result) {
    echo "Enter a different value";
} else {
    echo "Save successful.";
}
nickf
Aha, i've seen this before, and this definitely looks right. thanks nickf!
RobHardgood
Actually, is there any way to check if it's the specific error?
RobHardgood
Yep - `mysql_errno()` will return the error code of the last error. Off the top of my head, I don't know what that code is, but you could just check for that inside the `(!$result)` branch.
nickf
+1  A: 

To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:

mysql_query('INSERT INTO ...');
if (mysql_errno() == 1062) {
    print 'no way!';
}

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. MYSQL_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)

jensgram
Yeah, that's a good point.This didn't work though... are you sure 1022 is the right error code? I'll start looking too. Thanks
RobHardgood
Ah, it's `1062`, cf. http://dev.mysql.com/doc/refman/5.1/en/error-messages-server.html#error_er_dup_entry . Will edit answer.
jensgram
Yeah, I just found that too :D I plugged it in and it worked perfectly. Thanks jensgram, just the solution I was looking for!
RobHardgood
@RobHardgood You're welcome.
jensgram