You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter4中getLastQuery无法返回最后执行的SQL查询问题

解决CodeIgniter新版本获取最后执行SQL语句的问题

问题说明

你执行以下代码后,返回的是数据库对象而非期望的SQL语句:

$this->db->table($table)->set($set)->where('id', $id)->update();
return $this->db->getLastQuery();

返回结果示例:

"db":{"DBDriver":"MySQLi","connID":{},"resultID":true,"protectIdentifiers":true,"escapeChar":"`","likeEscapeStr":" ESCAPE '%s' ","likeEscapeChar":"!","dataCache":[],"transEnabled":true,"transStrict":true,"deleteHack":true,"mysqli":{},"resultMode":0,"numberNative":false,"save_queries":true}

而你需要像旧版CodeIgniter的last_query()那样,返回类似UPDATE tableSETf= 'v' WHEREid = 'id'的SQL字符串。

解决方案

  1. 确保查询保存功能开启
    检查app/Config/Database.php配置文件,确认$saveQueries设置为true:

    public $saveQueries = true;
    

    只有开启该配置,框架才会记录执行过的查询语句。

  2. 获取SQL字符串的正确方式
    新版本中getLastQuery()返回的是Query对象,需要调用其getQuery()方法提取SQL字符串:

    $this->db->table($table)->set($set)->where('id', $id)->update();
    return $this->db->getLastQuery()->getQuery();
    
  3. 额外场景:获取预编译SQL
    若需在执行查询前获取带占位符的预编译SQL,可使用getCompiledUpdate()方法:

    $sql = $this->db->table($table)->set($set)->where('id', $id)->getCompiledUpdate();
    $this->db->table($table)->set($set)->where('id', $id)->update();
    return $sql;
    

内容的提问来源于stack exchange,提问作者stackunderflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:00:01