matfish Posted September 19, 2006 Share Posted September 19, 2006 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 Quote Link to comment Share on other sites More sharing options...
Barand Posted September 19, 2006 Share Posted September 19, 2006 First you need a function to generate a random code. As an example, this generates random strings $size characters long[code]<?phpfunction 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 Quote Link to comment Share on other sites More sharing options...
matfish Posted September 19, 2006 Author Share Posted September 19, 2006 Your the man!Thanks, Ill give this a go!Many thanks Quote Link to comment Share on other sites More sharing options...
matfish Posted September 19, 2006 Author Share Posted September 19, 2006 Works great - thanks so much! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.