php - 在 php 中循环 - 创建不同的卷号

标签 php html mysql loops

这是我的代码:

$roll = rand(100,1000000);

$result = mysql_query("SELECT roll FROM users") or die(mysql_error());

if($row["roll"] == $roll) {
   $roll = rand(100,1000000);
}
else
{
  mysql_query("INSERT INTO users (roll) VALUES('$roll') ") or die(mysql_error()); 
}

echo "Data Inserted!";

我的问题是:

如果重新生成的卷号再次等于数据库中已存在的卷号,它应该如何再次生成新的卷号并继续检查它,除非它获得一个唯一的编号,我最终可以将其插入数据库?请帮忙!

最佳答案

您不必每次都获取所有卷。这只是浪费资源。只需检查数据库中是否存在 roll,如果存在,则检查一个新的。

function doesRollExist($roll) {
    $sql = "SELECT COUNT(*) FROM users WHERE roll = " . (int)$roll;
    $result = mysql_query($sql);
    if ($result) {
        return ((int)mysql_result($result, 0)) != 0;
    }
    else {
        trigger_error("Query failed: " . mysql_error(), E_USER_ERROR);
    }
}

do {
    $newRoll = mt_rand(100, 1000000);
}
while (doesRollExist($newRoll));

// Now $newRoll will be a random number that doesn't exist
// in the database.

关于php - 在 php 中循环 - 创建不同的卷号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17378184/

相关文章:

html - IE9 Bug div 在悬停 anchor 标记时跳转

php - 如何最小化我的查询?

Php Mysql分页

javascript - 使用 onsubmit 或 onclick 打开窗口基于使用输入

javascript - 我 << 1 在 Javascript 中是什么意思?

MySQL 与 group by 的案例

MySQL基于多返回值子查询的delete语句

php - 7 数字API签名无效

php - Wordpress 正在使用 index.php 而不是 single.php 来发布帖子

javascript - 比较用 ASP 编写的 html 实体和 JS 读取的 html 实体