When you encounter the error message “Call to a member function row_array() on bool” in PHP, it means that you are trying to use the method “row_array()” on a boolean value (i.e., true or false). This error typically occurs when the result of a database query is not as expected and returns a boolean value instead of a result set.
To understand this error better, let’s take an example of using CodeIgniter’s database query builder methods:
$query = $this->db->get('users'); // Running a query to retrieve user records
if ($query->num_rows() > 0) {
$user = $query->row_array(); // Trying to retrieve a single row as an associative array
echo $user['name'];
} else {
echo "No users found.";
}
In the above example, $query->get(‘users’) retrieves user records from the database. If there are no matching records, a boolean value (false) is returned. In such a case, calling the “row_array()” method on a boolean value will result in the error “Call to a member function row_array() on bool.”
To fix this error, you should make sure that the query executed successfully and returned a valid result set before calling any row retrieval methods. One way to do this is by checking the number of rows using the “num_rows()” method as shown in the example. This ensures that the query returned a positive number of rows before attempting to retrieve a specific row.
$query = $this->db->get('users');
if ($query !== false && $query->num_rows() > 0) {
$user = $query->row_array();
echo $user['name'];
} else {
echo "No users found.";
}
By adding the condition “$query !== false” before checking the number of rows, we ensure that the query did not result in a boolean value (i.e., false). This way, we avoid calling the “row_array()” method on a boolean (false).