Search code examples
phpcodeigniteractiverecordquery-buildercodeigniter-4

how to get last query in codeigniter 4?


This is my current code:

public function index()
{
    $tbl = 'm_trx';
    $db = \Config\Database::connect();
    $builder = $db->table($tbl);
    
    $data = [];

    $cols = "{$tbl}.*";
    $builder->select($cols);

    $data = $builder->get()->getResult();
    $asd = [
        'message' => $builder->getLastQuery(),
        'data' => $data,
    ];
    return $this->respond($asd);
}

but it returns error

"message": "Call to undefined method CodeIgniter\\Database\\MySQLi\\Builder::getLastQuery()",

if I changed $builder->getLastQuery() into $builder->db->getLastQuery() it returns this error instead

"message": "Cannot access protected property CodeIgniter\\Database\\MySQLi\\Builder::$db",


Solution

  • You only need to pass $db and not $builder->db

    Try this

    $db->getLastQuery()