php – 优惠券系统的随机码生成器
发布时间:2020-12-13 16:13:30 所属栏目:PHP教程 来源:网络整理
导读:这对于随机优惠券代码生成器来说是否足够好?在制作新代码时,我应该检查并查看代码是否已被使用?这会重复的几率是多少? $coupon_code = substr(base_convert(sha1(uniqid(mt_rand())),16,36),7); 编辑 – 这是我的实际代码: $coupon_code = substr(base_c
这对于随机优惠券代码生成器来说是否足够好?在制作新代码时,我应该检查并查看代码是否已被使用?这会重复的几率是多少?
$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())),16,36),7); 编辑 – 这是我的实际代码: $coupon_code = substr(base_convert(sha1(uniqid(mt_rand())),7); $numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1")); if($numrows>0){ $coupon_code = substr(base_convert(sha1(uniqid(rand())),7); $numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1")); if($numrows>0) //error,show link to retry } 解决方法
这是一个优惠券系统,不仅可以保证唯一的代码,而且在查找时非常有效:
// assuming MySQL table with (id,code,effect) mysql_query( "insert into `coupons` set `effect`='".$effect."'"); // "effect" will be some keyword to identify what the coupon does $id = mysql_insert_id(); $code = $id."F"; $codelen = 32; // change as needed for( $i=strlen($code); $i<$codelen; $i++) { $code .= dechex(rand(0,15)); } mysql_query( "update `coupons` set `code`='".$code."' where `id`=".$id); // now,when you are given a code to redeem,say $_POST['code'] list($code,$effect) = mysql_fetch_row( mysql_query( "select `code`,`effect` from `coupons` where `id`='".((int) $_POST['code'])."'")); if( $code != $_POST['code']) die("Code not valid"); else { // do something based on $effect } 如您所见,它从AUTO_INCREMENT获取ID,附加F,然后使用随机十六进制字符填充.您可以根据需要制作$codelen,但32应该足够(即使在第100万张优惠券之后也可以提供大约16 ** 26种组合). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |