找出mysqli INSERT失败的原因-重复了哪个唯一索引? [英] Finding out why a mysqli INSERT failed - which unique index was duplicated?

查看:74
本文介绍了找出mysqli INSERT失败的原因-重复了哪个唯一索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在编写一个REST风格的php服务器,该服务器需要允许用户注册.基本工作正常,但我现在专注于错误处理.我的用户表在"user_name"字段和"user_email"字段上具有唯一索引.当我尝试插入重复值时,我可以读取错误并得到类似

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

键"user_name"的条目"noggin182"重复

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.

推荐答案

如果您要尝试执行我认为您要尝试执行的操作,则可能值得采用其他方法,并增加添加逻辑的逻辑.用户通过一次交易进入存储过程,并事先进行任何检查以查看该用户是否已经存在.

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.

这篇关于找出mysqli INSERT失败的原因-重复了哪个唯一索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆