Search code examples
phpcodeigniter-4

Codeigniter4 - getLastQuery not return last sql query


I get this

"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}}

after run this

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

I expect it to return this instead

"UPDATE `table` SET `f` = 'v' WHERE `id` = 'id'"

like the way they did with older better Codeigniter

return $this->db->last_query();

Solution

  • What you're getting returned from $this->db->getLastQuery(); is a query object. The easiest way to get the last query from that object is to cast it to string:

    return (string) $this->db->getLastQuery();
    

    which does the same as:

    return $this->db->getLastQuery()->getQuery();
    

    The great thing about getting back a query object instead of the actual query is that it expands possibilities on what you can get out of it. Really handy, especially for debugging. For example

    $this->db->getLastQuery()->getOriginalQuery();
    

    to get the raw statement before any processing or

    $this->db->getLastQuery()->getDuration();
    

    to find slow queries.

    Documentation on query objects