若检查select查询的语句被忽略


If statement that checks select query is being ignored

我得到了以下代码:

if(isset($_POST['vote'])){
        if (!$wgUser->isLoggedIn()) {
            // User is not online, don't accept the vote, set error message
            $msg = 'Login required to vote.';
        } if ($wgUser->isBlocked()) {
            // User is banned, don't accept the vote, set error message
            $msg = 'Account is banned.';
        } else {
            // User is online and not banned
            $buildId = htmlspecialchars($_POST['id'], ENT_QUOTES, 'UTF-8');
            $rating = htmlspecialchars($_POST['rating'], ENT_QUOTES, 'UTF-8');
            $comment = htmlspecialchars($_POST['comment'], ENT_QUOTES, 'UTF-8');
            $res = $db->select(
                'build_rating',
                array('article_id', 'username', 'vote', 'comment', 'date'),
                array('article_id' => $buildId, 'username' => $wgUser->getName()),
                __METHOD__
            );
            // Did user already vote on this build?
            if (!$res) {
                // Yes, let's update the vote and set success message
                $db->update(
                    'build_rating',
                    array('vote' => $rating, 'comment' => $comment),
                    array('article_id' => $buildId, 'username' => $wgUser->getName()),
                    __METHOD__
                );
                $msg = 'Your vote has been successfully updated.';
            } else {
                // No, let's insert the vote and set success message
                $db->insert(
                    'build_rating',
                    array('article_id' => $buildId, 'username' => $wgUser->getName(), 'vote' => $rating, 'comment' => $comment),
                    __METHOD__
                );
                $msg = 'Your vote has been successfully saved.';
            }
        }
    }

用于保存用户对特定文章的评分。除了if语句之外,一切似乎都正常工作,if语句检查用户是否已经投票(在这种情况下,它应该更新评级)或是否是全新的投票(在那种情况下,应该将其保存为新的投票)。由于某种原因,if语句不起作用,因为每张选票都被保存为新的选票。一个用户可以简单地放置100个投票,而事实上他应该只能放置一个文章。有人能指出我的错误吗?

我不确定那是什么数据库库,但可能对select()的调用会返回迭代器。

if (count($res) == 0) {
    // update    
}

我设法解决了这个问题,您需要输入以下if ($res->numRows())

您也可以使用selectRow()而不是select(),而不是按照建议计算$res中的行数。selectRow将返回(第一个)匹配行,如果没有,则返回false。

只需使用upsert();这将在单个查询中执行选择/插入/更新组合。PHP代码看起来会更简单,操作将是原子操作,这将避免所有恶劣的竞争条件错误。