使用mysqli时is_resource函数校验失败的原因排查
mysqli查询结果检查失败的原因及修复方案
问题根源
你用is_resource()检查mysqli查询结果是错误的——mysqli扩展执行查询成功后返回的是mysqli_result对象,不是PHP传统意义上的资源类型,所以is_resource($this->db_qry)永远返回false,导致你的检查逻辑失败,最终返回false。
代码修复步骤
1. 修正结果判断逻辑
把原来的资源检查替换为对象类型判断,同时兼容无结果集的SQL语句(如INSERT/UPDATE/DELETE):
if ($this->db_qry instanceof mysqli_result) { return $this->db_qry; } else { // 对于无结果集的语句,mysqli_query成功会返回true return true; }
2. 复用数据库连接,避免重复连接
你的代码每次执行查询都重新创建连接,既浪费资源又可能触发连接数限制。改为先检查已有连接是否有效:
// 替换原连接代码 if (!isset($this->db_conn) || !mysqli_ping($this->db_conn)) { $this->db_conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name); if (!$this->db_conn) { return false; } }
3. 移除无用代码与规范变量使用
- 删掉无意义的
$sql = sprintf('%s', $sql); - 直接用
$this->db_conn作为mysqli_query的连接参数,不要依赖全局变量$GLOBALS["___mysqli_ston"]
修复后的完整代码
function exec_query($sql) { // 检查SQL是否为空 if (empty($sql)) { $this->close_conn(); return false; } // 复用或创建数据库连接 if (!isset($this->db_conn) || !mysqli_ping($this->db_conn)) { $this->db_conn = mysqli_connect($this->db_host, $this->db_user, $this->db_pass, $this->db_name); if (!$this->db_conn) { return false; } } // 执行查询 $this->db_qry = mysqli_query($this->db_conn, $sql); if (!$this->db_qry) { // 可在此处记录错误信息:mysqli_error($this->db_conn) return false; } // 判断结果类型并返回 if ($this->db_qry instanceof mysqli_result) { return $this->db_qry; } else { return true; } }
内容的提问来源于stack exchange,提问作者Jesse
相关产品推荐
相关产品推荐

