PHP MySQL如果等于其他INSERT

时间:2013-09-06 13:26:44

标签: php mysql

我有以下代码:

<?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子句中为更新指定目标表'user'

我用它来竞争从数据库中选择一个随机用户,但我现在需要它来查看所有用户,看看是否有一个用户的胜利者列等于1,如果没有一个用户应该选择随机用户并用1更新用户获胜列。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我正在使用mysql_query()函数,因为您在示例中使用了它。你应该阅读PDO并实现它。

根据我上面的评论,

require_once "connect_to_mysql.php"; 
// look for records with `winner` set to 1
$result = mysql_query('SELECT id, fullname, email, number FROM user WHERE winner = 1 LIMIT 1') or die (mysql_error());
if (mysql_num_rows($result) < 1) { // if no records were found, pick a random row
    $result = mysql_query('SELECT id, fullname, email, number FROM user ORDER BY RAND() LIMIT 1');
}

答案 1 :(得分:1)

我不知道你的赢家列实际存储了什么,但假设它是一个布尔值,可能只包含0或1,你可以在一个查询中执行此操作:

SELECT id, fullname, email, number FROM user ORDER BY winner DESC, RAND() LIMIT 1;

将会:

  • 对获胜者列中的所有记录进行排序,使行赢得胜利者= 1第一次
  • 使用RAND()
  • 排序等于记录

因此,您将获得随机结果,优先考虑获胜者列等于“1”的记录。

修改

我很想念你的需要。

这里有两个不同的流程

  • 获得胜利者
  • 设置获胜者

你应该把它分成两个函数/方法

// Get the winner data
function getWinner()
{
    $sql = 'SELECT id, fullname, email, number FROM user winner=1';
    $query = mysql_query($sql);

    mysql_num_rows($result) == 1) {
        $user = mysql_fetc_assoc($query);           
        return $user;
    }

    return false;
}

function setWinner()
{
    $sql = 'UPDATE user SET winner=1 ORDER BY RAND() LIMIT 1';
    mysql_query($sql);
}

// Call this one time
setWiner();

// Call this any time you want to get the winner's data
$winner = getWinner();

更懒惰的方法是,如果没有赢家,将使getWinner()函数调用setwinner:

// Get the winner data
function getWinner()
{
    $sql = 'SELECT id, fullname, email, number FROM user winner=1';
    $query = mysql_query($sql);

    mysql_num_rows($result) == 1) {
        $user = mysql_fetc_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;
}

这取决于您的上下文,但从一般的角度来看,这是不好的做法,因为在某些情况下,看起来像读取数据(getSomething)的函数也会改变数据(调用setWinner()。