Welcome Guest, Not a member yet? Register   Sign In
Bug in count_all() and count_all_results()
#1

[eluser]voidstar[/eluser]
In CI 1.7.0 both count_all() and count_all_results() use the returned value from $this->query() without first checking if it's FALSE, which can result in a fatal error.

For example if the user misspells a MySQL table name, count_all() will fail on line 332 of mysql_driver.php.

If the user misspells a field name
$this->db->where('nonexistent', 'value'); // field does not exist
$total = $this->db->count_all_results('valid_table_name');
count_all_results() will fail on line 1030 of DB_active_rec.php.

In both cases this unfortunate outcome could be easily avoided, e.g. in count_all_results()

$query = $this->query($sql);
$this->_reset_select();
if ($query == FALSE) return FALSE; // FIX


It would also be helpful if the Active Record documentation demonstrated how to get the MySQL error message in the event of a failure. For example with the fix above

$total = $this->db->count_all_results('table_name');
if ($total === FALSE)
{
$this->error_message[] = 'Count failed: ' . $this->db->_error_message();
// remainder of error reporting
}
#2

[eluser]Phil Sturgeon[/eluser]
If I mis-spell a field name in my code, I would much rather it failed and told me about it, than returning FALSE - which could also be interpreted as 0 if not careful.
#3

[eluser]voidstar[/eluser]
I understand your concern, but...
- A quick survey of the methods in the Active Record class reveals that they call $this->query() to actually perform the database operation. $this->query() can return FALSE, and in most cases ( except count_all() and count_all_results() ) this boolean is returned to the application. Asking the caller of the count_all() and count_all_results() methods to check for FALSE is no different from asking him to check the return code from any other active record method.
- Without this fix the developer knows that there's been an error, but he has no idea what it is. The resulting error message and stack dump are not pretty.

Fatal error: Call to a member function num_rows() on a non-object in C:\xampp\htdocs\CodeIgniter_1.7.0\system\database\drivers\mysql\mysql_driver.php on line 332

With this fix the caller can at least retrieve the MySQL error message and get some useful information, e.g.

Table 'codeigniter.xxx' doesn't exist




Theme © iAndrew 2016 - Forum software by © MyBB