Jump to content


Photo

Random code != already got *solved*


  • Please log in to reply
3 replies to this topic

#1 matfish

matfish
  • Members
  • PipPipPip
  • Advanced Member
  • 242 posts
  • LocationUK

Posted 19 September 2006 - 09:30 AM

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

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,022 posts

Posted 19 September 2006 - 10:23 AM

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


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

To speed things up, add an index on disc_code column in your table
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 matfish

matfish
  • Members
  • PipPipPip
  • Advanced Member
  • 242 posts
  • LocationUK

Posted 19 September 2006 - 10:45 AM

Your the man!

Thanks, Ill give this a go!

Many thanks

#4 matfish

matfish
  • Members
  • PipPipPip
  • Advanced Member
  • 242 posts
  • LocationUK

Posted 19 September 2006 - 11:29 AM

Works great - thanks so much!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users