View Single Post
Old 01-07-2009, 11:09 PM   #8 (permalink)
Wildhoney
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
Wildhoney is on a distinguished road
Box

Taking the above ideas into consideration. How about the following? To get it working, merely import the attached SQL file and then change the MySQL details on lines 43 and 44.

php Code:
class TalkPHP_UniqueKeyGenerator
{
    public static function make()
    {
        $aChars = range('A', 'Z');
        $aRange = array_merge($aChars, range(0, 9));
       
        shuffle($aRange);
       
        $aSegments = array
        (
            implode('', array_slice($aRange, 0, 8)),
            $aChars[rand(0, count($aChars) - 1)]
        );
       
        $szKey = implode('', $aSegments);
       
        mysql_query(sprintf("INSERT INTO report (hash) VALUES ('%s')", $szKey));
        $iPrimaryKey = mysql_insert_id();
        mysql_query("UPDATE report SET hash = CONCAT(hash, last_insert_id()) WHERE id = last_insert_id()");
       
        return $szKey . $iPrimaryKey;
    }
   
    public static function get($szKey)
    {
        preg_match('~.+?(\d+)$~i', $szKey, $aMatches);
       
        if (empty($aMatches))
        {
            return false;
        }
       
        $pResult = mysql_query(sprintf("SELECT * FROM report WHERE id = %d", (int) $aMatches[1]));
        $aResult = mysql_fetch_row($pResult);
       
        return isset($aResult[0]) ? $aResult[0] : false;
    }
}
   
mysql_connect('localhost', 'Username', 'Password');
mysql_select_db('Database');

$szGeneratedKey = TalkPHP_UniqueKeyGenerator::make();
printf('Incident Report ID Set: %s<br />', $szGeneratedKey);
printf('Incident Report ID Get: %d (PK)', TalkPHP_UniqueKeyGenerator::get($szGeneratedKey));

MySQL table creation code if you don't wish to download the SQL file:

sql Code:
CREATE TABLE `report` (
  `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `hash` varchar(16) NOT NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `hash` (`hash`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
Attached Files
File Type: sql TalkPHP_UniqueKeyGenerator.sql (924 Bytes, 131 views)
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is offline  
Reply With Quote