开发者

How to handle mysql's error on duplicate entry?

Sometimes开发者_Python百科 when there's an entry about to be added to the database it failed because it's a duplicate entry, an error shows up. So, how to handle this error with the help of php?


You can use mysql_errno() to get the error number, and mysql_error() to get the error message. Using these, you can determine when the error is "Duplicate." A list of error numbers can be online - just do a ctrl + f and search the word "duplicate" to find the various error numbers.


You said you wanted to deal with the issue in PHP but it is good to be aware that there are possibilities also on the MySQL side. I have found that with either INSERT IGNORE or ON DUPLICATE KEY UPDATE I can avoid needing to handle MySQL errors in PHP.


It kind of depends on what you mean by "handling it in PHP".

The obvious and simple answer, which has already been answered, is to watch for an error message and work forward from there.

Whilst this can work, I think a better solution is to figure out what actions in your PHP applciation could produce this. Is it a race condition? Is it an assumption that is sometimes wrong? Is it guessing about an inserted value instead of figuring out the correct one? Is it a result of the end-user doing something not thought and thus not being caught and erroring? Is it the application using the database in ways it was not designed for?

All of these have solutions that do not involve catching the MySQL error and trying to figure out how to fix what went wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜