27

How can I get last query I ran in MySQL in both Windows and Linux?

I am working with PHP and CodeIgniter. In my_model.php, I have:

$query1 = ( ...something... );
$query2 = ( ...something... );
$variables = ( .... something .... );
$this->db->query(" $query1 ... $variables .. $query2", array( $variables, ... ));

I need the last query executed right after the code snippet above.

Can anyone tell me how can I get my last query?

4
  • As far as I know, there is no generic "get the last query" function. What do you need it for?
    – Pekka
    Jun 30, 2011 at 14:37
  • 1
    @Pekka, CodeIgniter has this built-in :-)
    – gen_Eric
    Jun 30, 2011 at 14:40
  • @Rocket ah, fair enough.
    – Pekka
    Jun 30, 2011 at 14:40
  • Other useful functions if your are debugging are mysql_errno(); // Returns the error number of the last MySQL operation 3 mysql_error(); // Returns the error description of the last MySQL operation mysql_info(); // Returns information about the last query Jun 30, 2011 at 14:42

3 Answers 3

64

Use:

$this->db->last_query();

Returns the last query that was run (the query string, not the result). Example:
$str = $this->db->last_query();

// Produces: SELECT * FROM sometable.... 

example taken from the manual on query helper functions

3
  • got this: PHP Fatal error: Uncaught Error: Call to undefined method mysqli::last_query() Jul 24, 2020 at 13:37
  • @AhmadAmeri Note that the answer refers to a 9 years ago version of Codeignter, and PHP. Jul 24, 2020 at 14:00
  • do you have any idea how can i get latest query? Jul 24, 2020 at 14:15
3

In CodeIgniter there is a helper function $this->db->last_query();.

This will return the string of the last query.

But I think you might be asking how to obtain the result, in which case you'd do:

$query1 = ( ...something... );
$query2 = ( ...something... );
$variables = ( .... something .... );
$query = $this->db->query(" $query1 ... $variables .. $query2", array( $variables, ... ));

foreach ($query->result() as $row) {
//code goes here
}

For more information, take a look a CI's examples.

3

In the config/database.php the config array must be set: 'save_queries' => TRUE, if it is false not working the last_query() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.