Jump to content


This topic is now archived and is closed to further replies.


Random code != already got *solved*

Recommended Posts


Anyone point me in the right direction to create a random 6 char (letters and numbers) code thats not already in a database? Its a discount code, which needs to be 6-8 chars; letters and numbers to insert into a database which is not already being used.

Many thanks

Share this post

Link to post
Share on other sites
First you need a function to generate a random code. As an example, this generates random strings $size characters long
function genDiscountCode($size) {
    $a = array_merge(range('A', 'N'), range('1','9'), range('P', 'Z'), range('1','9'));
    $code = '';
    $b = array_rand($a,$size);
    foreach($b as $k) $code .= $a[$k];
    return $code;

Then you need keep generating codes until you get one that hasn't been used
    do {
        $code = genDiscountCode(6) ;
        $res = mysql_query("SELECT COUNT(*) FROM mytable WHERE disc_code = '$code'") or die(mysql_error());
    } while (mysql_result($res,0) > 0);
    // use generated code
    echo $code;

To speed things up, add an index on disc_code column in your table

Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.