Reputation: 73
I have a submission form that returns a MySQL error #1062 when a user tries to submit it with a duplicate entry. As an example, the error states:
Duplicate entry 'graphics' for key 'name'
I want to give the user a custom message that explains (in plain English) why they got an error, and what specific entry caused the error. For example:
"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form."
The key will always be 'name,' but the duplicate entry itself will often be different. I need to be able to pull that specific value out of the MySQL error that's generated, and then wrap my custom message around it. How could this be done?
Upvotes: 2
Views: 1082
Reputation: 2116
you can check the table first before entering any data if the items you are inserting exist beforehand .
and second you can then print a custom message according to the error using if else loop like
$check_exists = // runs the code here to check if the entry graphics already exists for the existing name
if ($post['name'] == ''){
// error message for blank entry
}elseif($check_exists == true) {
// custom error mesage for duplicate entry
}else {
// submit the form here
}
Upvotes: 0
Reputation: 1044
You could try to make a simple error check, displaying the user your error message if a mysql error occurs. You could try something like this:
$rows = mysql_query("SELECT `name` from `tbl` WHERE `name` = 'graphics';");
if(mysql_num_rows($rows) > 0){
echo '"Graphics" is a duplicate entry and should not be used. Please remove it and resubmit the form.';
}else{
insert...
}
Upvotes: 4