doukongyong44772 2013-03-11 06:56
浏览 28
已采纳

如何使用PHP / MySQL基于表的行创建特定大小的随机数?

I want to create a specific-sized random "key" for every row in the database table. For example, for the "id" or row (auto-increment ID) "20", the column "key" will have "xEd456" and for row 21, it will be e.g. "rYU875". However, I also want to make sure there is no way there is a duplicate "key" in the table. I prefer to have 6-char "key". How do I achieve this?

  • 写回答

1条回答 默认 最新

  • dsfgdsjfd78773 2013-03-11 06:58
    关注

    That means you need a alphanumeric key, see the code

    while(true)
      {
      $str="";
      for($i=0;$i<6;$i++)
        {
        $rnd=rand(1,16);
        if(intval(fmod($rnd, 2)))
        $a=rand(48,57);
        else
        $a=rand(65,90);
        $str .= chr($a);
        }
      // skipping the mysql connection functions
      $sql=mysql_query(“select user_id from user_master_table where user_id_alias='".$str."'");
      $rs=mysql_fetch_array($sql);
      if($rs["user_id"]=="")
        break;
      }
    

    You are free to change the loop value and random number range.

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

报告相同问题?

悬赏问题

  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥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美术毛发渲染