我想实施一个新的推荐/促销系统.我的新系统,当用户注册一个特定的来源时,他就会得到他的帮助.来源可以是来自referal(客户域)和促销代码(例如:50%折扣)的任何内容.此来源还有一个日期(ymd).每个源ID都是唯一的,多个用户可以拥有相同的源ID
例如:
source id : 1 = www.domain1.com / 2011-11-20 / (empty referal code)
source id : 2 = www.domain1.com / 2011-11-20 / referalcode1
source id : 3 = www.domain2.com / 2011-11-20 / referalcode1
source id : 4 = www.domain2.com / 2011-11-20 / referalcode2
Run Code Online (Sandbox Code Playgroud)
可以将referal代码从client1混合到客户端2
我如何确定当有人注册(它的免费注册,我们现在每小时超过1000)我们没有重复记录并冒险mysql产生错误?
Boo*_*eus 25
从mysql页面:
主要思想是使用该
ignore
语句插入记录.如果使用IGNORE关键字,则执行INSERT语句时发生的错误将被视为警告.例如,如果没有IGNORE,则复制表中现有UNIQUE索引或PRIMARY KEY值的行会导致重复键错误,并且语句将中止.使用IGNORE时,仍未插入行,但未发出错误.然后使用检索最后一个IDmysql_insert_id
如果记录不存在,它将插入它并返回最后一个ID.
现在,如果没有返回记录,您可以进行选择.这意味着记录已经存在,所以只需使用它即可.
例:
// make sure $id is safe (preventing sql injections)
$sql = "INSERT IGNORE INTO yourtable SET `field1` = 'value1' ... ";
mysql_query($sql);
if(mysql_affected_rows() == 1) { // no record found and then the inserts worked
$id = mysql_insert_id(); // id from the primary key
// add to cache
}
else {
// you can also cache them when they were inserted (faster to run than a select statement)
$id = retreiveFromCache($field1, $field2 /* etc...*/);
if(!$id) { // no record found in cache
// now the select can be done using the fields received
// make sure your use the right index otherwise it can be slow
$sql = "SELECT id FROM promotions_referrals WHERE `field1` = 'value1' ... "; //
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$id = $row['id'];
// add to cache
}
}
Run Code Online (Sandbox Code Playgroud)
此时您将$id
被分配,并且您确定没有重复/ mysql错误.
注意:如果域属于一个客户端,请使用客户端ID而不是使用域.这样,您将使用INT作为索引,该索引比VARCHAR快.推荐代码的想法相同.