[英]How to validate and insert new random value if it is present in database
This is my code 这是我的代码
$lclReferCode = rand(100000,999999);
function random(){
$lclReferCode1 = rand(100000,999999);
return $lclReferCode1;
}
$lclReferCode = random();
$lclQuery = "SELECT * FROM `sign_up` WHERE us_refer_code = '$lclReferCode'";
$qryResult = mysql_query($lclQuery);
if(mysql_num_rows($qryResult) == 0){
$lclQuery = "INSERT INTO sign_up(us_refer_code) values('" . $lclReferCode . "')";
$qryResult = mysql_query($lclQuery);
}else{
random();
}
Here my intention is to insert unique values not the duplicates. 我的目的是插入唯一值,而不是重复值。 Before inserting I am checking the database if this random number is present already or not if it is present I have to generate new values again I have to generate values and match if not present then the insert query executes. 插入之前,我正在检查数据库是否已经存在此随机数(如果存在),我必须再次生成新值,我必须生成值并匹配(如果不存在)然后执行插入查询。 can anyone help me. 谁能帮我。
Like this (untested): 像这样(未经测试):
function setRandom(\PDO $PDO){
$stmt = $PDO->prepare("SELECT * FROM `sign_up` WHERE us_refer_code = :us_refer_code");
try{
$stmt->execute([':us_refer_code' => rand(100000,999999)]);
}catch(\PDOException $e){
if($e->getCode() == 23000){ //if I recall right this is duplicate key
setRandom($PDO); //<-- recursive.
}else{
//if not duplicate key re-throw the error.
throw new \PDOException($e->getMessage(), $e->getCode(), $e);
}
}
}
But you have to use PDO, with the error mode set to exception, and with the database field defined as a unique index. 但是您必须使用PDO,将错误模式设置为exception,并且将数据库字段定义为唯一索引。
It might not be a bad idea to build in a recursion limit, as you could get in a situation where it never finds a value not entered in the DB. 建立递归限制可能不是一个坏主意,因为您可能会遇到这样的情况:它永远找不到未在数据库中输入的值。 That would look like this. 看起来像这样。
function setRandom(\PDO $PDO, $limit=0){
if($limit > 1000) throw new \Exception(__FUNCTION__.' recursion limit exceeded');
$stmt = $PDO->prepare("SELECT * FROM `sign_up` WHERE us_refer_code = :us_refer_code");
try{
$stmt->execute([':us_refer_code' => rand(100000,999999)]);
}catch(\PDOException $e){
if($e->getCode() == 23000){ //if I recall right this is duplicate key
setRandom($PDO, ++$limit);//<-- recursive
}else{
//if not duplicate key re-throw the error.
throw new \PDOException($e->getMessage(), $e->getCode(), $e);
}
}
}
This would give it 1000 tries before throwing an exception. 这将在抛出异常之前进行1000次尝试。 It's never good to have code that has a real possibility of creating infinite recursion. 拥有真正创建无限递归的代码永远都不是一件好事。
On my sites I have a error handler that shoots me an email if I have any uncaught exceptions. 在我的网站上,我有一个错误处理程序,如果我有任何未捕获的异常,它会向我发送电子邮件。 So I would know right away. 所以我马上就会知道。 Of coarse this is optional and some of this is tightly coupled to your particular use case. 粗略地说,这是可选的,其中有些与您的特定用例紧密相关。
Otherwise you will have to use a select inside of a while loop. 否则,您将不得不在while循环中使用select。 like this (Also untested). 像这样(也未经测试)。
/**
* return false or the random value to use.
* @return false|int
*/
function ckRandom($lclReferCode){
$lclReferCode = rand(100000,999999);
$lclQuery = "SELECT * FROM `sign_up` WHERE us_refer_code = '$lclReferCode'";
$qryResult = mysql_query($lclQuery);
if(mysql_num_rows($qryResult) == 0){
//no result means the number is not used yet.
return $lclReferCode;
}else{
return false;
}
}
//$limit = 0;
$lclReferCode = false;
while( false === $lclReferCode){
$lclReferCode = ckRandom();
//if($limt > 1000) throw new \Exception(' recursion limit exceeded');
//++$limit;
}
//if $lclReferCode IS NOT false then it is the last random number searched that had no results in the DB
$lclQuery = "INSERT INTO sign_up(us_refer_code) values('" . $lclReferCode . "')";
See the idea is the while loop will trap execution until the result returns something other then 0, if it's 0 then no row exists. 看到的想法是while循环将捕获执行,直到结果返回0以外的值,如果为0则不存在任何行。 (you have this backwards). (您有这个倒退)。
And again, this is prone to infinite recursion. 同样,这很容易导致无限递归。 I added the "limit" stuff in comments. 我在评论中添加了“限制”内容。
That said, I would strongly suggest doing away with any mysql_
functions as they wont work post PHP7. 就是说,我强烈建议您mysql_
任何mysql_
函数,因为它们在PHP7之后将无法使用。
you need to try like this 你需要这样尝试
function random(){
$lclReferCode = rand(100000,999999);
$lclQuery = "SELECT * FROM `sign_up` WHERE us_refer_code = '$lclReferCode'";
$qryResult = mysql_query($lclQuery);
$checkRow=mysql_num_rows($qryResult);
if ($checkRow>0) {
return random();
}else{
$lclQuery = "INSERT INTO sign_up(us_refer_code) values('" . $lclReferCode . "')";
$qryResult = mysql_query($lclQuery);
return true;
}
}
if (random()===true) {
echo 'inserted succesfully';
}
remember this is demonstration.i recommend to you use mysqli
or pdo
because mysql
is not valid in php7
记住这是演示。我建议您使用mysqli
或pdo
因为mysql
在php7
中php7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.