我有以下代码:
<?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);
?>
尝试使用 g4vroche 的答案但收到此错误:您无法在 FROM 子句中指定目标表“用户”进行更新
我用它来竞争从数据库中选择一个随机用户,但我现在需要它来查看所有用户,看看是否有一个用户的获胜者列等于 1,如果没有,它应该选择随机用户并将用户获胜者列更新为 1。
非常感谢任何帮助。