php - 查询返回结果,但对给出的布尔值发出警告
问题描述
我正在尝试将旧应用程序升级到 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
解决方案
mysqli_query 返回值:如果可以mysqli_result object
,,,true
false
失败时返回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,或将其更新为正确的
推荐阅读
- r - 如何使用 r 在数据框中获取嵌套循环的输出?以及如何放置时间循环?
- python - Python 值错误:没有足够的值来解压,适用于 linux 但不能在 Windows 上运行
- jquery - 模态事件关闭后如何使切换选项恢复默认值?
- django - 当搜索字段为空时,Django SearchFilter 正在显示所有数据
- javascript - Vue.js axios 获取服务器的动态IP
- python - 如果值不存在,如何退出 for 循环?
- bash - 从字符串中第二次出现的破折号中提取字符
- node.js - 在尝试了很多命令后,我得到了同样的错误(nodemon:找不到命令)
- javascript - 请参阅 HTML 中的 Node-js 值
- wordpress - 当他们的订单准备好在 woocommerce 中交付时,有没有办法接受客户的全额付款?