Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 唯一随机id_Php_Global Variables_Scope - Fatal编程技术网

Php 唯一随机id

Php 唯一随机id,php,global-variables,scope,Php,Global Variables,Scope,我正在为我的小应用程序生成唯一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,但我面临一些可变范围的问题。我的代码-

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

这看起来不像是变量范围问题,它看起来像是一个简单的变量分配问题:

$count=0;
while($count == 1)
{
这一块显然永远不会执行

此外,在进行布尔检查时,请使用具有良好名称的布尔值。它读起来非常干净。i、 e:

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\u查询将使用上次使用的连接:
无需将其设置为全局。

根据Zak的回答,我将把用户名传递到函数中,而不是使用全局

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

编辑:现在我想起来了:您希望如何找到
“从ruser中选择*,其中userId='$id';”
?Select查询用于查找特定的内容,您的用户名是如此随机,我认为实际成功获取记录的可能性是百万分之一。

edit2哎呀,我明白了关键是要获得一个唯一的用户名。。。O_O

除其他外:

$count =mysql_query($sqlcheck,$link)or die(mysql_error());  
mysql_查询不返回记录计数,而是返回资源


这个代码有很多问题,但通过练习你会变得更好:)奇怪,自动增量有什么问题吗?似乎出于某种原因,他的意图是混淆唯一的ID。auto_inc不会混淆。为什么要用这种方式创建唯一ID我不知道。。。也许是因为以后你想设定一个很难猜到的曲奇?最好只使用内置的sessionID功能。。。此外,您可能应该阅读文档中的php会话安全部分:致命错误:在C:\xampp\htdocs\303\rand.phpok中超过了60秒的最大执行时间,您对如何找出这超过60秒的原因的第一个想法是什么?你为什么不发布一个新问题来解释你在做什么以及你遇到的问题呢。包括页面的新完整源代码。这也会给你一个机会,让你在一个新问题上有新的代表。
$count =mysql_query($sqlcheck,$link)or die(mysql_error());