6

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());
rostamiani
  • 2,859
  • 7
  • 38
  • 74
  • *"My query always generates NULL"*? maybe `county.name` should be `country.name`. *"What's the $db? It's not defined in the controller"*? you could define it like this: `$db=$this->db;` – Vickel Jan 31 '20 at 16:47
  • `echo $this->db->getLastQuery();` – Hamza Zafeer Jul 07 '21 at 12:52

8 Answers8

10

This should display the final query:

$cityModel->getLastQuery()->getQuery()
DivPusher
  • 156
  • 2
  • 5
5

In CI 4 Refer Doc

you can use getLastQuery() as

$query = $db->getLastQuery();
echo (string)$query;
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37
2

This code will help you to get the last query in codeigniter 4.

 $this->db = \Config\Database::connect();
 $data = $builder->get()->getResult();
 echo $this->db->getLastQuery(); die;
cottton
  • 1,522
  • 14
  • 29
Wprog_dy
  • 67
  • 5
1

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

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

Following Code will work in CI 4

$this->db->getLastQuery()->getQuery();
Piyush Bansal
  • 1,635
  • 4
  • 16
  • 39
0

Simply just use $this->db->getLastQuery();

James Risner
  • 5,451
  • 11
  • 25
  • 47
Tanay Syed
  • 19
  • 6
0

This worked for me

$myModel = new MyModel();// your any model
    
$myModel->db->getLastQuery()->getQuery();

$this->db is not directly accessible from controller, but if you have any Model instance then you can have the full access to db object.

Asif Thebepotra
  • 300
  • 3
  • 10
  • What's the difference between this approach and Piyush's answer from September? Doesn't `$this` translate to `$myModel` in this case? – Jeremy Caney Dec 22 '22 at 17:41
  • 1
    In My Case, `$this->db` was not accessible from Controller, I need to create instance for it. But I tried with my Model instance and it worked. – Asif Thebepotra Dec 22 '22 at 17:55
  • 1
    That's useful to know. I'd recommend [edit]ing your answer to include that information so that it's clear upfront how it differs from Piyush's answer. – Jeremy Caney Dec 23 '22 at 00:45
-1

Add this code in your class

$db = \Config\Database::connect();
$query = $db->getLastQuery();
echo $query;
fajarra
  • 11
  • 3