如果选择的随机用户已经在获奖者表中,我需要以下代码循环并选择另一个随机用户。
以下代码有效,但如果它随机选择已经在获奖者表中的用户,则不会再次尝试。我尝试了几种不同的方法,但没有找到有效的解决方案。
提前致谢。 (这是我关于stackoverflow的第一个问题,如果我没有遵循任何协议,请轻松告诉我)
<?php
$host="localhost";
$user_name="db_user";
$pwd="db_pass";
$database_name="db_name";
$db=mysql_connect($host, $user_name, $pwd);
if (mysql_error() > "") print mysql_error() . "<br>";
mysql_select_db($database_name, $db);
if (mysql_error() > "") print mysql_error() . "<br>";
$sqlCommand = "SELECT userid, firstname, surname, email FROM users ORDER BY RAND() LIMIT 1";
$query = mysql_query($sqlCommand) or die (mysql_error());
while ($row = mysql_fetch_array($query)) {
$userid = $row["userid"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$email = $row["email"];
$checkuserid = mysql_query("SELECT userid from winners WHERE userid=$userid");
if (mysql_num_rows($checkuserid)==0) {
$sqlCommand = "INSERT into winners (userid, firstname, surname, email) values ('" . $userid ."','" . $firstname . "', '" . $surname . "', '" . $email . "')";
mysql_query($sqlCommand) or die (mysql_error());
} else {
}
}
mysql_close();
header("Location: http://mysite.com"); /* Redirect browser */
exit();
?>
答案 0 :(得分:3)
您可以在一个查询中执行此操作:
INSERT INTO winners
SELECT userid, firstname, surname, email
FROM users
WHERE userid NOT IN (SELECT userid FROM winners)
ORDER BY RAND()
LIMIT 1
Please, don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:2)
您可以通过将$sqlCommand
替换为:
$sqlCommand = "SELECT userid, firstname, surname, email ".
"FROM users ".
"WHERE userid NOT IN (SELECT userid FROM winners) ".
"ORDER BY RAND() LIMIT 1";
答案 2 :(得分:1)
您可以更改第一个查询,以使用NOT EXISTS排除另一个表中的用户。
http://dev.mysql.com/doc/refman/5.0/en/exists-and-not-exists-subqueries.html
看起来应该是这样的
SELECT userid, firstname, surname, email FROM users WHERE NOT EXISTS (SELECT * FROM winners
WHERE users.userid = winners.userid) ORDER BY RAND() LIMIT 1;
此外,您的代码无效,因为它只有一个循环,因为限制1
答案 3 :(得分:1)
如果你想要一个循环,把代码片段从`$ sqlCommand'语句放到另一个循环中while循环的末尾。