Jump to content

Random code != already got *solved*


matfish

Recommended Posts

Hi,

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
Link to comment
Share on other sites

First you need a function to generate a random code. As an example, this generates random strings $size characters long
[code]<?php
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;
}
?>
[/code]

Then you need keep generating codes until you get one that hasn't been used
[code]
<?php
    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;
?>[/code]

To speed things up, add an index on disc_code column in your table
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.