开发者

unique random id

开发者 https://www.devze.com 2022-12-30 08:26 出处:网络
I am generating unique id for my small application but I am facing some variable scope problem. my code-

I am generating unique id for my small application but I am facing some variable scope problem. my code-

function cr开发者_如何学运维eate_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;  

I dont know which variable I have to declare as global


That doesn't look like a variable scope problem, it looks like a simple variable assign problem:

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

This block will clearly never execute.

Further, please use a boolean with a good name when doing boolean checks. It reads so much cleaner. 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 );
}

Note that mysql_query will use the last used connection if you don't specify a link: http://us2.php.net/mysql_query No need to make it global.


in adition to Zak's answer i'd pass the username into the function instead of using globals

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

also

//$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);

edit: now that i think of it: how do you expect to find "Select * FROM ruser WHERE userId='$id';"? A Select query is used to find something specific, your username is so random, i think the likely hood of actually successfully getting a record is 1 in a bajillion.
edit2 whoops, i see the whole point is to get a unique username... O_O


In addition to the others:

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

mysql_query doesn't return a record count but, rather, a resource.

mysql_query

0

精彩评论

暂无评论...
验证码 换一张
取 消