【问题标题】:unique random id唯一的随机 id
【发布时间】:2011-02-20 12:22:03
【问题描述】:

我正在为我的小型应用程序生成唯一 ID,但我遇到了一些可变范围问题。我的代码-

function create_id()
{  
global $myusername;  
$part1 = substr($myusername, 0, -4);  
$part2 = rand (99,99999);  
$part3 = date("s");  
return $part1.$part2.$part3;  
}

$id;  
$count=0;

while($count == 1)  
{  
$id;  
$id=create_id();  
$sqlcheck = "Select * FROM ruser WHERE userId='$id';";  
$count =mysql_query($sqlcheck,$link)or die(mysql_error());  
}  


echo $id;  

我不知道我必须将哪个变量声明为global

【问题讨论】:

  • 这段代码有很多问题
  • 你会通过练习变得更好:)
  • 很好奇,auto_increment 有什么问题?
  • 他的意图似乎是出于某种原因混淆唯一 ID。 auto_inc 不会混淆。

标签: php global-variables scope


【解决方案1】:

这看起来不像是变量作用域的问题,它看起来像是一个简单的变量赋值问题:

$count=0;
while($count == 1)
{

这个块显然永远不会执行。

此外,在进行布尔检查时,请使用具有良好名称的布尔值。它读起来干净多了。即:

function isUniqueUserID($userIDToCheck)
{
    $sqlcheck = "Select * FROM user WHERE userId='$userIDToCheck';";  
    $resource = mysql_query($sqlcheck)or die(mysql_error()); 
    $count = mysql_fetch_assoc($resource);
    if( count($count) > 0)
    {return false;}

    return true;
}


$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
     $userIDToCheck = create_id();
     $userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}

请注意,如果您不指定链接,mysql_query 将使用上次使用的连接: http://us2.php.net/mysql_query 无需使其全球化。

【讨论】:

  • 为什么你要以这种方式创建唯一 ID 我不知道......也许是因为以后你想设置一个难以猜测的 cookie?最好只使用已经内置的 sessionID 功能...此外,您可能应该阅读文档中的 php 会话安全部分:us2.php.net/manual/en/session.security.php
  • 致命错误: C:\xampp\htdocs\303\rand.php 中的最大执行时间超过 60 秒
  • 好的,您首先想到的是如何找出为什么这需要超过 60 秒的时间?你为什么不发布一个新问题来解释你在做什么以及你遇到的问题。包括页面的新完整源代码。这也会让您有机会在新问题上获得一些新的代表。
【解决方案2】:

除了 Zak 的回答,我会将用户名传递给函数而不是使用全局变量

function create_id($username)
{
    $part1 = substr($username, 0, -4);  
    $part2 = rand (99,99999);  
    $part3 = date("s");  
    return $part1.$part2.$part3;  
}

还有

//$id;  no need for this
$count=1; // this bit

while($count == 1)   // not sure what's going on
{  
//$id; again same thing  no need for this
$id=create_id($myusername);

编辑: 现在我想起来了:你希望如何找到"Select * FROM ruser WHERE userId='$id';"?选择查询用于查找特定内容,您的用户名是如此随机,我认为实际成功获得记录的可能性是 1 in a bajillion.
edit2 哎呀,我看到了全部关键是要获得一个唯一的用户名... O_O

【讨论】:

    【解决方案3】:

    除此之外:

    $count =mysql_query($sqlcheck,$link)or die(mysql_error());  
    

    mysql_query 不返回记录计数,而是返回资源。

    mysql_query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-14
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-19
      相关资源
      最近更新 更多