I need the following code to loop back and select another random user if the random user it selects is already in the winners table.
The below code works but if it randomly selects a user that is already in the winners table, it doesn't try again. I have tried a few different ways but haven't found a solution that works.
Thanks in advance. (this is my first question on stackoverflow, please go easy on me if I have failed to follow any protocols)
<?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();
?>