0

I need to generate an alpha numeric string and compare with database values but if the value is present in database then we should generate a different numeric string and again it should be compared with database values....

<?php
$character_array = array_merge(range('a', 'z'), range(0, 9));
$Emp_Id = "";
for($i = 0; $i < 6; $i++) {
    $Emp_Id .= $character_array[rand(0, (count($character_array) - 1))];} ?>

which is working fine by creating an alpha numeric code,But as i have mentioned above i need to compare it with database values.

$chkEmp_Id=mysql_fetch_array(mysql_query("SELECT Emp_Id FROM talent_users WHERE   Emp_Id='{$Emp_Id}' "));

after comparing with database values if the value is present then it should generate a different "Emp_Id",every time generated employee id should be compared with database values...hope u guys got it na?please help me to fix this...

Elias Van Ootegem
  • 67,812
  • 9
  • 101
  • 138
  • 1
    You should stop using `mysql_*` functions. They're being deprecated. Instead use [PDO](http://php.net/manual/en/book.pdo.php) (supported as of PHP 5.1) or [mysqli](http://php.net/manual/en/book.mysqli.php) (supported as of PHP 4.1). If you're not sure which one to use, [read this SO article](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons). – Matt Aug 06 '12 at 13:18
  • shehzad and matt can you guyzz please give me an example which can fix this problem...? –  Aug 06 '12 at 13:20
  • 2
    Why don't you let the database generate a unique value for you? Why does it need to be so "random"? This is a really inefficient design choice as the comparison is going to get costlier and costlier as the table size grows. – Aaron Bertrand Aug 06 '12 at 13:22
  • Hello Aaron, we need to generate unique values from php.Thats the only option to for our project.:) –  Aug 06 '12 at 13:29

1 Answers1

0
$pool = array_merge (range ('a', 'z'), range(0, 9));

do
{
    $hash = "";
    for ($i = 0; $i < $lengthOfHash; ++$i)
    {
        $hash .= $pool[array_rand ($pool)];
    }
while ( mysql_result (mysql_query ('SELECT COUNT(1) FROM talent_users WHERE Emp_Id = ' . $hash), 0) > 0);

But this is a big bottleneck when the table size grows. Since the hash is alpha-numeric, why can't the hash just begin with the userId?

//hash = <a number> + <a letter> + <alpha-numeric chars>
$hash = $userId . generateHash();

Just make sure that the generateHash() function doesn't start with a number, as stated in the comment.

It would then be something like:

$hash = $userId;
$letters = range ('a', 'z');
$pool = array_merge ($letters, range (0, 9));

for ($i = 0; $i < $lengthOfHash; ++$i)
{
    $chooseFrom = $pool;

    if ( ! $i )
        $chooseFrom = $letters;

    $hash .= $chooseFrom[array_rand($chooseFrom)];
}
DavidS
  • 1,520
  • 11
  • 25