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字符串。
解决方案
确保查询保存功能开启
检查app/Config/Database.php配置文件,确认$saveQueries设置为true:public $saveQueries = true;只有开启该配置,框架才会记录执行过的查询语句。
获取SQL字符串的正确方式
新版本中getLastQuery()返回的是Query对象,需要调用其getQuery()方法提取SQL字符串:$this->db->table($table)->set($set)->where('id', $id)->update(); return $this->db->getLastQuery()->getQuery();额外场景:获取预编译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
相关产品推荐
相关产品推荐

