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.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看