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

标签 php random

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

$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/

相关文章:

php - 简单的MySQL查询和比较

python - scipy.stats 是否为不同的计算机硬件产生不同的随机数?

r - `rbinom()` 中可能存在大量试验的错误

php - 如何使用php生成随机人名?

php - mysql_connect() : No such file or directory in/opt/lampp/htdocs/

php - Mysql - 唯一索引或列

php - 是否可以在 codeigniter 中用 where 条件计算所有?

php - PHP 中的 preg_replace - NOT 条件的正则表达式

python-3.x - 从给定的 n 个元素数组中随机选择一个数字,概率与其大小成正比

c# - 我将如何创建一个程序来获取名称列表并将它们分类为偶数组?