dongtun2459 2012-12-01 07:39
浏览 51
已采纳

如何正确检查是否采用了用户名?

I'm using PHP/MySQL. What is the best way to check if the username is already taken?

Right now all I do is execute a select statement to see if the username is already taken. If the select returns a row then I stop and display an error message. If the select doesn't return anything then I insert the new user.

But is there a more efficient way? For example can I use UNIQUE on the username column and then only execute an insert statement(and get an error from the insert if it's already taken).

  • 写回答

1条回答 默认 最新

  • dongqianchi0512 2012-12-01 07:48
    关注

    You do have the risk that some other thread will insert your user name in the brief moment between your SELECT confirming that the user doesn't exist and the INSERT where you insert it. This is called a race condition.

    It may seem like the chance of that happening is slight, but there's a saying about that: "One in a million is next Tuesday."

    Yes, a UNIQUE constraint on the username can prevent you from INSERTing a duplicate username. Declare that constraint.

    Some articles will tell you that once you have a UNIQUE constraint, you don't have to do the SELECT anymore. Just try the INSERT and if it conflicts, then report the error.

    However, I helped a site recover from a problem caused by this technique. On their site, users were attempting to create new usernames very quickly, and resulting in a lot of conflicts on the INSERT. The problem was that MySQL increments the auto-increment primary key for the table, even if the INSERT was canceled. And these auto-increment values are never reused. So the result was that they were losing 1000-1500 id numbers for every INSERT that succeeded. They called me when their INT primary key reached 231-1 and they couldn't create another row in the table!

    The solution they used was first to try the SELECT, and report a duplicate. Then if it seemed safe, try the INSERT -- but write the code to handle the possible conflict with the UNIQUE constraint anyway, because the race condition can still occur.

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路