Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I have a SQL statement in my model,

I then say

$query = $this->db->query($sql, array(fields, fields1);

if ($query) {

    return true:

} else {

    echo "failed";

    return false;

}

My query always fails, how do I get PHP to print the exact SQL statement being sent to my database? And display that on my PHP view, page

2 Answers

0 votes
by (40.7k points)

Use the below query to display the query string:

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

To display the query result follow this:

print_r($query);

The Profiler Class can display benchmark results, queries you have run, and $_POST data at the bottom of your pages. 

To enable the profiler place the below line anywhere within your Controller methods like this:

$this->output->enable_profiler(TRUE);

Profiling user guide: https://www.codeigniter.com/user_guide/general/profiling.html

You can learn in-depth about SQL statements, queries and become proficient in SQL queries by enrolling in our industry-recognized SQL online course.

0 votes
by (1.5k points)

To print the exact SQL query in CodeIgniter and troubleshoot why it’s failing, you can follow these steps:

Use $this->db->last_query(): This function shows the last executed SQL query, including the values from any bound parameters

Update Your Model Code: Modify your code to output the SQL query if it fails, as shown below:

$query = $this->db->query($sql, array(fields, fields1));

if ($query) {

   return true;

} else {

   // Display the SQL query that was executed

   echo "Failed. The query was: " . $this->db->last_query();

   return false;

}

Enable Debugging for More Details:

Set 'db_debug' => true in application/config/database.php. This will show detailed database errors directly in the browser, helping with troubleshooting.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Dec 19, 2020 in SQL by Appu (6.1k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...