duan0514324 2014-08-10 00:26
浏览 98
已采纳

PHP / MySQLi - 捕获唯一ID冲突

I'm wondering if there's an easy way to check if an INSERT statement triggers a conflict due to a unique index on a MySQL field while performing the INSERT.

For example, say I'm adding a user to a database, and username is a unique index:

$sql = new MySQLi(...);
$res = $sql->query('INSERT INTO `users` (`username`) VALUES ("john_galt");');

A user named john_galt already exists, so the INSERT won't be performed. But how can I best respond to the user with a meaningful error (i.e. A user with that username already exists; please choose a unique name.)?

I thought of a couple things, like checking if insert_id is set -- which it shouldn't be if the query generated an error. But that error could be anything.

Similarly, I could check to see if $sql->error is not empty, except, again, that could be anything as well -- a syntax error, or a malformatted value, or whatever. Obviously I'm not going to print out the actual MySQL error for the end user.

The two solutions I can think of are:

  • Before running the INSERT, run a SELECT TRUE FROM ``users`` WHERE ``username`` = "john_galt"; to see if the username already exists in the database, but I feel like I added a unique constraint to the field so that I wouldn't have to do this -- kinda defeats the purpose otherwise.
  • strpos($sql->error, 'Duplicate entry') === 0 -- seems horribly hackish.

Is there a better method for determining this using PHP's MySQLi class?

  • 写回答

1条回答 默认 最新

  • doupapin172773 2014-08-10 00:34
    关注

    You can use errno to get the returned error code and use that, for example:

    if($sql->errno === 1062) {
        //do something
    }
    

    Here's a list of error codes for MySQL 5.5: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要