random alphanumeric value generator

From: Date: Mon, 26 Jan 2004 23:00:35 +0000
Subject: random alphanumeric value generator
Groups: php.general 
Request: Send a blank email to php-general+get-175823@lists.php.net to get a copy of this message
Hi, I am trying to generate a non-sequential random alphanumeric value. Just to make things fun, I need to guarantee that each value is unique. I have a working solution, but it seems retarded to me because there is a small chance that 2 people might hit the same page at the same time, do separate inserts, but both get the same MAX(uiIndex) value. Is there a better way to do this? TIA, Craig table defn: create table randomKey ( uiIndex int unsigned auto_increment not null primary key, cKey char(20) unique ); function getKey() { //get random number into db. it is guaranteed //unique from db once result = true because //cKey is unique $query = 'INSERT INTO randomKey (cKey) VALUES (RAND())'; while (!$result = mysql_query($query, dbConnect($errorMsg))) { //do nothing, just loop until result = true } //now get the random number, and MD5 it to get it alphanumeric $query = 'SELECT MAX(uiIndex), cKey FROM randomKey GROUP BY cKey'; $result = mysql_query($query, dbConnect($errorMsg)); $row = mysql_fetch_object($result); return md5($row->cKey); }

« previous php.general (#175823) next »