Debugging ActiveRecord queries in CodeIgniter

Posted: 2009-05-29
Category: CodeIgniter

When you have an ActiveRecord call that just will not work, it can be a pain. Many developers seem to find an issue and instantly ask for help, which often takes a great deal longer than it would to work it out on your own.

To save asking questions on the CodeIgniter forums that you could solve yourself, try these steps:

1.) Output the final query and see if it looks right. Do this after your model call or within the model after $this->db->get().

// Clear any existing output (optional)
ob_clean();

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

// Stop PHP from doing anything else (optional)
exit();

2.) If it looks fine, try running it in phpMyAdmin or another GUI.

3.) If it fails, you get an error message from MySQL server telling you what’s wrong. It will make it pretty obvious what change needs to be made to get it working.

4.) If it runs fine, then CodeIgniter is not running the query correctly. This could:

a.) CodeIgniter is logged into MySQL with a different user who may not have the same permissions.

b.) A condition is not being met in your model file or controller that is stopping the query from being run. Output values along the way.

Debugging is a wonderful thing CodeIgniter fans, follow these steps and you'll solve any query issues you come accross.

Comments

Gravatar
Andy Wright

2009-07-29

Hi,

This is built into CI. Try adding the following into any controller:

<?php $this->output->enable_profiler(TRUE);
?>

It outputs the full SQL Query for you plus other useful info.

http://codeigniter.com/user_guide/general/profiling.html

Gravatar
Alex

2010-02-09

Thank you!
This line helped me: CodeIgniter is logged into MySQL with a different user who may not have the same permissions.

Gravatar
Ian

2010-03-12

@Andy Wright that code snippet was just what I need to get out of a problem. Thanks :-)

Gravatar
Vishnu

2012-06-07

Unfortunately the debugging methods provided above does not solve my problem. When I try to run a simple query using '$this->db->query(" ")', the executiuon just stops there and lines after the query do not get executed. No Logs, Errors or anything. Able to run same query in mysql cline.

Gravatar
Holly

2012-12-10

$this->db->last_query(); was exactly what I was looking for and saved me a whole lot of time! Thank you!

Posting comments after three months has been disabled.