首页 > 解决方案 > 查询返回结果,但对给出的布尔值发出警告

问题描述

我正在尝试将旧应用程序升级到 PHP 7.2。它包含一个 sql 类 PHP 文件,其中包含我已修改为使用 mysqli 的以下函数:

    function query($query, $index=0)
    {
        // query
        if (!$this->res[$index] = mysqli_query($this->connection, $query))
        {
            // if query fails show error
            $this->error('<strong>invalid query</strong>:<br />' . $query . '<br />');
            return false;
        }

        // statistical information
        $this->num_rows[$index] = @mysqli_num_rows($this->res[$index]);
        $this->num_flds[$index] = @mysqli_num_fields($this->res[$index]);
        $this->num_aff[$index]  = @mysqli_affected_rows($this->connection);
        $this->last_id             = @mysqli_insert_id($this->connection);

        return true;
    }

此函数引发以下错误:

E_WARNING Error in file �sql.class.php� at line 132: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given E_WARNING Error in file �sql.class.php� at line 133: mysqli_num_fields() expects parameter 1 to be mysqli_result, boolean given

我最初的想法是查询失败。但是,在函数中包含这一行......

print_r(mysqli_fetch_assoc($this->res[$index]));

产生以下输出:

Array ( [s_id] => 2088b4cc0d026c2742e8e0cb7d7c8e95 )

在上面的输出中,查询返回一个会话 ID。这让我有点困惑,因为值$this->res[$index]不是布尔值,但警告说它是。

编辑:

如果我将其包含在函数中:

        echo mysqli_num_rows($this->res[$index]);
        echo mysqli_num_fields($this->res[$index]);

每行都回显正确的值,1但每行也会产生布尔警告...

E_WARNING Error in file �sql.class.php� at line 125: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
E_WARNING Error in file �sql.class.php� at line 126: mysqli_num_fields() expects parameter 1 to be mysqli_result, boolean given

标签: phpmysqlmysqli

解决方案


mysqli_query 返回值:如果可以mysqli_result object,,,truefalse

失败时返回FALSE。对于成功的 SELECT、SHOW、DESCRIBE 或 EXPLAIN 查询,mysqli_query() 将返回一个mysqli_result 对象。对于其他成功的查询 mysqli_query() 将返回TRUE

尝试此修改以查看哪个查询真正成功但结果为

function query($query, $index=0)
{
    $this->res[$index] = mysqli_query($this->connection, $query);
    // query
    if (is_bool($this->res[$index])) {
        if ($this->res[$index] === false)
        {
            // if query fails show error
            $this->error('<strong>invalid query</strong>:<br />' . $query . '<br />');
            return false;
        } else {
            // query was successful, but the result is not a mysqli_result object
            $this->warning('<strong>success with no returned data query</strong>:<br />' . $query . '<br />');
            return true;
        }
    }


    // statistical information
    $this->num_rows[$index] = @mysqli_num_rows($this->res[$index]);
    $this->num_flds[$index] = @mysqli_num_fields($this->res[$index]);
    $this->num_aff[$index]  = @mysqli_affected_rows($this->connection);
    $this->last_id             = @mysqli_insert_id($this->connection);

    return true;
}

检查您的代码中是否存在$this->warning,或将其更新为正确的


推荐阅读