PHP致命错误求助:布尔值/字符串上调用成员函数问题排查
Hey there, let's tackle those two fatal errors you're facing in your user_model.php file. I'll break down what's causing each one and show you how to fix them step by step.
Error 1: PHP Fatal error: Call to a member function result() on boolean
This happens because CodeIgniter's $this->db->query() method returns false when your SQL query fails—common culprits include syntax errors, typos in table/column names, missing database permissions, or malformed query strings. You're trying to call result() on that boolean false value, which isn't allowed.
Quick Fix for Error 1:
Always validate the query result before calling methods like result():
// Replace your line 46 code with this $query_result = $this->db->query($query); // Check if the query executed successfully if ($query_result !== false) { $users = $query_result->result(); // Proceed with your subscription validation logic here } else { // Debug the error to identify the root cause var_dump($this->db->error()); // Shows raw SQL error details // For production, log the error instead of dumping it log_message('error', 'Package Expire Query Failed: ' . $this->db->error()['message']); }
Error 2: PHP Fatal error: Call to a member function num_rows() on a string
This error means you're trying to call num_rows() on a string value instead of a CodeIgniter database result object. The most likely causes are:
- You accidentally assigned a string to the variable you're using
num_rows()on (e.g., echoing the query string and reusing it later). - You're calling
num_rows()on$users(an array returned byresult()) instead of the original query result object.
Quick Fix for Error 2:
num_rows() is a method of the query result object, not the array returned by result(). Use it like this:
$query_result = $this->db->query($query); if ($query_result !== false) { $valid_user_count = $query_result->num_rows(); // Correct way to get row count $users = $query_result->result(); // This gives you an array of user objects // Do NOT call $users->num_rows() — this will throw an error! }
Additional Debugging & Best Practices
Inspect Your Raw SQL: Print the
$querystring before execution to catch syntax errors:echo $query; // Shows the exact SQL being sent to the database die(); // Pause execution to inspect the queryLook for unclosed quotes, missing clauses (like
FROM), or typos in table/column names.Use CodeIgniter's Query Builder: Instead of writing raw SQL strings, use the query builder to avoid syntax mistakes and reduce SQL injection risks:
// Example for your subscription validity check $query_result = $this->db->select('*') ->from('customers') // Replace with your actual table name ->where('subscription_end_date <', date('Y-m-d')) // Check expired ->or_where('subscription_status', 'invalid') // Check invalid ->get();Verify Database Permissions: Ensure your database user has
SELECTaccess to the table you're querying.
内容的提问来源于stack exchange,提问作者Suraj Sharma

