Wednesday, 4 December 2013

Generate a unique alphanumeric string by checking against the database in PHP

<?php

//function to generate n character alpha-numeric string.

function alphamumeric($length=12) {
   $charset = '1234567890abcefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($charset), 0, $length);
}

//assuming we are storing the generated ids in the column 'id' of table 'tbl_ids' in database 'test'

$mysqli=new mysqli('localhost','root','root','test');

do{

$num=alphamumeric(16);
$query="SELECT count(id) FROM tbl_ids WHERE id='$num'";
$result=$mysqli->query($query);
$row=$result->fetch_row();
$found=$row[0];

}while($found == 1);

echo 'Unique Id='.$num;

?>

For the Id to be unique you must check it with the database or file where you are storing the Ids (collision check). Otherwise, you can't be sure that the currently generated value is unique.

After the do-while loop ends, the variable $num gives you a 16 character unique id.

Please note that in the code

   $charset = '1234567890abcefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';

1234567890 has been repeated three times.This is just to increase the probability of 'numeric characters' relative to 'non-numeric characters' in the generated value. If you use 1234567890 only once, you will notice that there are mostly non-numeric characters generated.

document.write() overwrites the entire page

document.write is a function which basically outputs whatever is given to it. But sometimes, improper usage may overwrite the entire page d...