Hi
I've got the following, untested code. I want to know if this will work, and if there is a better way of doing what I'm trying to do? I'm afraid this might trigger itself into endless loops? Wouldn't it be better to split this into two seperate subs?
The sub is suppose to create a random ID, check the ID colum of a MySQL table to see if the ID already exists. If it doesn't it returns normally, if it does it should go through the sub again until a random ID is found.
$randlet = chr(65 + int(rand(26))) . chr(65 + int(rand(26)));
$randnum = 1000000 + int(rand(8999999));
$randid = $randlet . $randnum;
&connect_to_db;
$sth = $dbh->prepare("SELECT id FROM bs_sessions");
$sth->execute();
my $count = 0;
while (my $ref = $sth->fetchrow_hashref ())
{
if ($randid eq $ref->{id}) {
$count + 1;
}
}
$sth->finish();
if ($count) {
&get_unique_id;
exit;
}
return $randid;
}
Rgds
Wil Stephens
- wil
I've got the following, untested code. I want to know if this will work, and if there is a better way of doing what I'm trying to do? I'm afraid this might trigger itself into endless loops? Wouldn't it be better to split this into two seperate subs?
The sub is suppose to create a random ID, check the ID colum of a MySQL table to see if the ID already exists. If it doesn't it returns normally, if it does it should go through the sub again until a random ID is found.
Code:
sub get_unique_id { $randlet = chr(65 + int(rand(26))) . chr(65 + int(rand(26)));
$randnum = 1000000 + int(rand(8999999));
$randid = $randlet . $randnum;
&connect_to_db;
$sth = $dbh->prepare("SELECT id FROM bs_sessions");
$sth->execute();
my $count = 0;
while (my $ref = $sth->fetchrow_hashref ())
{
if ($randid eq $ref->{id}) {
$count + 1;
}
}
$sth->finish();
if ($count) {
&get_unique_id;
exit;
}
return $randid;
}
Rgds
Wil Stephens
- wil