Home >Database >Mysql Tutorial >How Can I Print SQL Statements from CodeIgniter Models for Debugging?
Printing SQL Statements in CodeIgniter Models
In CodeIgniter models, it can be beneficial to print the exact SQL statement being sent to the database, especially during troubleshooting or debugging. To accomplish this, you can utilize the last_query() method.
In your model, you can include the following code:
$sql = 'SELECT * FROM users WHERE id = ?'; $query = $this->db->query($sql, array($id)); if (!$query) { $error_message = 'Query failed: ' . $this->db->last_query(); // Handle error... }
The last_query() method returns the most recent SQL statement that was executed. By appending it to an error message, you can easily identify the problematic statement.
To display the printed SQL statement on your view page, you can use the following approach in your controller:
$error_message = 'Query failed: ' . $this->db->last_query(); $this->load->view('error_view', array('error_message' => $error_message));
In your error_view, you can then echo the $error_message to display the full SQL statement for inspection.
The above is the detailed content of How Can I Print SQL Statements from CodeIgniter Models for Debugging?. For more information, please follow other related articles on the PHP Chinese website!