CodeIgniter报错:在布尔值上调用num_rows()方法求助
Let's break down why you're hitting this error and how to fix it step by step.
What's Causing the Error?
The Call to a member function num_rows() on boolean error happens because your database query is failing. When CodeIgniter's $this->db->get() encounters a broken SQL query, it returns false (a boolean) instead of a valid result set object. Trying to call num_rows() on that boolean value throws the error you see.
Step 1: Debug the Generated SQL
First, let's see exactly what SQL CodeIgniter is trying to run. Add these lines right before $this->db->get() in your method:
echo $this->db->last_query(); die();
Copy the output and run it directly in your database client (like phpMyAdmin or MySQL Workbench). This will show you the exact syntax error or missing table/field causing the query to fail.
Step 2: Fix the Query Issues
Looking at your code, there are two key adjustments needed:
- Disable Automatic Escaping for Complex Queries: CodeIgniter's query builder automatically escapes identifiers, which can break subqueries like yours. Add
falseas the second parameter to$this->db->select()to prevent this. - Add Error Handling: Check if the query succeeded before calling
num_rows().
Here's the revised version of your method:
public function out_of_stock_count(){ // Disable auto-escaping to preserve subquery syntax $this->db->select(" b.manufacturer_name, a.product_name, a.generic_name, a.strength, ( (SELECT IFNULL(SUM(quantity), 0) FROM product_purchase_details WHERE product_id = a.product_id) - (SELECT IFNULL(SUM(quantity), 0) FROM invoice_details WHERE product_id = a.product_id) ) AS stock ", false); $this->db->from('product_information a'); $this->db->join('manufacturer_information b', 'b.manufacturer_id = a.manufacturer_id', 'left'); $this->db->group_by('a.product_id'); $this->db->having('stock < 10'); $query = $this->db->get(); // Handle query failure gracefully if (!$query) { // Print database error for debugging (remove in production) echo $this->db->error()['message']; return 0; // Return a safe default or throw an exception } return $query->num_rows(); }
Additional Checks
- Verify that all tables referenced (
product_information,manufacturer_information,product_purchase_details,invoice_details) exist in your database. - Double-check that all field names (like
product_id,quantity,manufacturer_id) are spelled correctly across all tables. - If you're using a case-sensitive database (like PostgreSQL on Linux), ensure table/field names match the exact casing in your database.
内容的提问来源于stack exchange,提问作者Ehsan

