gpt4 book ai didi

php - 优惠券系统随机码生成器

转载 作者:可可西里 更新时间:2023-10-31 23:34:07 24 4
gpt4 key购买 nike

这对于随机优惠券代码生成器来说是否足够好?我在创建新代码时是否应该检查并查看代码是否已被使用?重复这种情况的几率有多大?

$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7);

编辑 - 这是我的实际代码:

$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 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())), 16, 36), 0, 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 种组合)。

关于php - 优惠券系统随机码生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com