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 Link to comment https://forums.phpfreaks.com/topic/21252-random-code-already-got-solved/ 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 Link to comment https://forums.phpfreaks.com/topic/21252-random-code-already-got-solved/#findComment-94527 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 Link to comment https://forums.phpfreaks.com/topic/21252-random-code-already-got-solved/#findComment-94539 Share on other sites More sharing options...
matfish Posted September 19, 2006 Author Share Posted September 19, 2006 Works great - thanks so much! Link to comment https://forums.phpfreaks.com/topic/21252-random-code-already-got-solved/#findComment-94555 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.