gpt4 book ai didi

php - 如果数据库中存在数字,则给出另一个随机整数 (PHP)

转载 作者:行者123 更新时间:2023-11-29 00:26:24 25 4
gpt4 key购买 nike

我正在尝试制作一个脚本来检查一个 int 是否已经添加到我的数据库中。如果是这样,它将重新生成另一个随机数并再次检查。如果它不存在,它将插入到数据库中。

但是,我遇到了麻烦。如果一个数字存在,它只是打印出 num exists,我将如何重新循环它以检查另一个然后插入那个?我尝试过使用continue;return true; 等等……无论如何,这是我的代码;希望有人能帮助我!

<?php
require_once("./inc/config.php");

$mynum = 1; // Note I am purposely setting this to one, so it will always turn true so the do {} while will be initiated.

echo "attempts: ---- ";

$check = $db->query("SELECT * FROM test WHERE num = $mynum")or die($db->error);

if($check->num_rows >= 1) {
do {

$newnum = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $newnum")or die($db->error);
if($newcheck->num_rows >= 1) {
echo $newnum . " exists! \n";
} else {
$db->query("INSERT test (num) VALUES ('$newnum')")or die($db->error);
echo "$newnum - CAN INSERT@!@!@";
break;
}

} while(0);
}
?>

最佳答案

我认为您正在寻找的逻辑基本上是这样的:

do {
$i = get_random_int();
} while(int_exists($i));
insert_into_db($i);

(想出一些函数名称通常有助于简化事情并理解真正发生的事情。)

现在只需用您的代码替换伪函数:

do {
$i = rand(1, 5);
$newcheck = $db->query("SELECT * FROM test WHERE num = $i")or die($db->error);
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);
$db->query("INSERT test (num) VALUES ('$i')") or die($db->error);

当然,您可以通过缩短......做更多的调整

// ...
if ($newcheck->num_rows >= 1) {
$int_exists = true;
} else {
$int_exists = false;
}
} while($int_exists);

...到:

// ...
$int_exists = $newcheck->num_rows >= 1;
} while($int_exists);

(>= 比较的结果是 bool 值,如您所见,您也可以将此值赋给一个变量,这样可以节省 4 行代码。)

此外,如果您想更进一步,请尝试用实际的、有意义的函数替换您的数据库调用,就像我在第一个示例中所做的那样。

这样,您的代码将变得更具可读性、紧凑性和可重用性。最重要的是,您可以通过这种方式了解更多有关编程的知识。

关于php - 如果数据库中存在数字,则给出另一个随机整数 (PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705048/

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