php - ..->num_rows 显示错误结果

标签 php mysql sql mysqli mysql-num-rows

我在 PHP 中创建了一个函数,用于检查数据库中是否存在记录。我用来获取行的查询是:

SELECT COUNT(*) AS Total, Conversation_ID FROM conversation WHERE User_ID = 3 AND With_User_ID = 4

现在,当我在 phpmyadmin 的 sql 选项卡中手动运行此查询时,我得到以下信息: result_of_running_query

该图像显示数据库中有一行与我的查询条件相匹配,这完全没问题。

现在,这是我的 PHP 函数:

public static function CheckIfConversationExists($userid, $withuserid) {
    if(Utilities::IsValid($withuserid) && Utilities::IsValid($userid)) {
        Database::OpenConnection();

        $userId = Utilities::SafeString(Database::$databaseConnection, $userid);
        $withUserId = Utilities::SafeString(Database::$databaseConnection, $withuserid);

        $query = Database::$databaseConnection->prepare("SELECT COUNT(*) AS Total, Conversation_ID FROM conversation WHERE User_ID = ? AND With_User_ID = ?");
        $query->bind_param("ii", $userid, $withuserid);
        $result = $query->execute();
        $query->bind_result($total, $conversationid);
        if($result && $query->num_rows > 0) {
            $id = array("Conversation_ID"=>"{$conversationid}");
            return json_encode($id);
        } else {
            return -1;
        }
        Database::CloseConnection();
    }
}

问题是当我回显 $query->num_rows 时我得到的结果是0因此我的函数总是返回-1。但是,正如您所看到的,我在数据库中运行的同一查询给出了一行。

现在让你明白,你会问函数中的值是否正确。是的,我已经检查了三次,在每个可能的地方重复它们,我得到的结果是相同的,即 3 and 4 .

你能帮我吗?

最佳答案

Returns the number of rows in the result set. The use of mysqli_stmt_num_rows() depends on whether or not you used mysqli_stmt_store_result() to buffer the entire result set in the statement handle.

http://www.php.net/manual/en/mysqli-stmt.num-rows.php

它计算使用mysqli_stmt_store_result()存储的结果,而不是实际的行。

添加 $query->store_result(); 之前。另请阅读第一条评论,这正是您的问题。

关于php - ..->num_rows 显示错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844765/

相关文章:

mysql - node.js/node_mysql - 过时的连接得到 "NO database selected"错误

mysql - 获取每组记录的行号

javascript - 如何在 sequelize 上使用实例方法

php - 如何通过android应用程序在mysql数据库中创建表?

php - base64 解码数组中的 2 个项目并仍然输出 json?

php - 需要在 Ubuntu 上使用 PHP 查找网络接口(interface)的 IP 地址

php - 响应速度不适用于 slider

mysql - SQL - 连接查询运行缓慢

javascript - 存储文件夹层次结构 laravel

sql - 声明和使用 MySQL varchar 变量