29

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?

1

3 Answers 3

71

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.