duanchen7036 2011-03-31 18:03
浏览 178

使用php为mysql数据库生成随机id

I have searched high and low for an answer with no avail.

I am trying to insert a random id number for my users between 9999,99999999. Problem is they have to be unique. I have everything set up but with an auto increment set for the id. I figured I will keep the auto increment field and just add another row for the unique id.

This is what I got so far:

$id = mt_rand(9999,99999999);

    $query = "SELECT * FROM accounts";

    $result = mysql_query($query) or die(mysql_error());

    while($account = mysql_fetch_array($result)){

        if ($id == $account['id']){

    $id = mt_rand(9999,99999999);

    } else {

    $sql = "INSERT INTO accounts (id, username, email, password, sex)
    VALUES ('$id', '$username', '$email', '$password', '$sex')";
    mysql_query($sql);}}

Now I figured if I create a random number, check the database if it exists create another, else insert it, but it is not working, if it a simple solution I apologise.

Thanks again :)

  • 写回答

4条回答 默认 最新

  • dtevhgk028372 2011-03-31 18:05
    关注

    this may seem like a silly answer:

    If you are already using auto_increment on a unique key, there is not a need to add another unique key

    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号