how to get last query in codeigniter 4?

Issue

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()

Answered By – Shoshana

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published