Search code examples
phpcodeigniteractiverecordcodeigniter-4

$this->db->last_query() returns NULL in Codeigniter 4. How to get query SQL?


I just started learning Codeigniter 4. My query always generates NULL and I don't know why. How can I see the generated SQL Select command just like Codeigniter 3?

In Codeigniter 3 this command does the job:

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

And this is my controller code in Codeigniter 4 that I need to get the generated query:

$cityModel = new CityModel();
$cities = $cityModel
    ->select('city.name AS cityName')
    ->select('county.name AS countryName')
    ->select('province.name AS provinceName')
    ->join('province', 'city.province_id = province.id', 'left')
    ->join('county', 'city.county_id = county.id', 'left')
    ->result();

Update: I tried this code but it's returning an empty string:

var_export((string)$cityModel->db->getLastQuery());

Solution

  • You can use getCompiledSelect it will return the query SELECT command.

    $sql = $cityModel->getCompiledSelect();
    echo $sql;