如果它选择的随机用户已经在获胜者表中,我需要以下代码循环并选择另一个随机用户。
下面的代码有效,但如果它随机选择一个已经在获胜者表中的用户,它不会再试一次。我尝试了几种不同的方法,但没有找到有效的解决方案。
提前致谢。(这是我关于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();
?>