I Have the following code:
<?php
error_reporting(E_ALL);
// connect to your MySQL database here
$dbhandle = mysql_connect('xxx', 'xxxx', 'xxxx');
$selected = mysql_select_db("xxxx",$dbhandle);
// Get the winner data
function setWinner(){
$sql = 'UPDATE user SET winner = 1 WHERE id=(SELECT id FROM user ORDER BY RAND())';
$query = mysql_query($sql) or die (mysql_error());
echo $query;
}
// Get the winner data
function getWinner()
{
$sql = 'SELECT id, fullname, email, number FROM user WHERE winner = 1';
$query = mysql_query($sql) or die (mysql_error());
if(mysql_num_rows($query) == 1) {
$user = mysql_fetch_assoc($query);
} else {
// If there is no winner yet, automatically create one
setWinner();
// Recall the function which should now find a winner
$user = getWinner();
}
return $user;
}
$winner = getWinner();
print_r($winner);
?>
Trying to work with g4vroche's answer but getting this error: You can't specify target table 'user' for update in FROM clause
I used this for a competition to select a random user from the database, but i now need it to look through all the users to see if there's a user that's winner column equals 1 and if there isn't one it should select the random user and update that users winner column with 1.
Any Help greatly appreciated.