Finding out why a mysqli INSERT failed - which uni

2019-09-08 11:59发布

问题:

I'm currently writing a REST style php server that needs to allow user registration. The basics are working but I am focusing on error handling now. My users table has a unique index on the 'user_name' field and the 'user_email' field. When I try to insert a duplicate value I can read the error and get a string like

Duplicate entry 'noggin182' for key 'user_name'

I need to translate this into something that I can display to the user. Is there is an easy way to get more details of why the insert failed? I could easily parse the string to find out but this feels messy, things would break if the string gets changed in an update or the language changes.

回答1:

If you're trying to do what I think you're trying to do, it might be worth taking a different approach, and putting the logic for adding a user in to a Stored Procedure, in a single transaction, and doing any checks beforehand to see if the user already exists.

You could then return your own logic as to whether the user added, or a reason why it couldn't be. Or raise your own error or something maybe.



回答2:

The error message normally contains more information

ERROR 1146 (42S02): Table 'test.no_such_table' doesn't exist

A numeric error code (1146). This number is MySQL-specific and is not portable to other database systems.

You could return this number and display the corresponding text on the client but normally what we do is catch the exception and log the full stacktrace but return only simple text to the client. Your users don't want to know that there was an attempted duplicate key insert as they can do nothing about that they want to know that the save failed and that the administrator of the site has been alerted to the problem as is looking into it and a solution will be forthcoming..



回答3:

because of unique key added on that column. unique does not allow duplicate data.

try this:

$query="select * from table where user_email='".$_POST["user_email"]."'";

$result=mysql_query($query);
if(mysql_num_rows($result)>0)
{
your insert query.....
}
else
{
echo "email already exists";
}


标签: php mysqli