diff --git a/README.md b/README.md index df7b354..9f3089b 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ Create a connection array or object similar to this: The parameters required depend on the database. ### Running Queries -Query uses the same interface as CodeIgniter's [Active Record class](http://codeigniter.com/user_guide/database/active_record.html). However, it does not implement the `count_all_results`, `having`, `or_having`, `insert_batch`, `update_batch` methods. +Query uses the same interface as CodeIgniter's [Active Record class](http://codeigniter.com/user_guide/database/active_record.html). However, it does not implement the `having`, `or_having`, `insert_batch` or `update_batch` methods. #### Retrieving Results diff --git a/classes/query_builder.php b/classes/query_builder.php index 79e8671..0ee79a1 100644 --- a/classes/query_builder.php +++ b/classes/query_builder.php @@ -1045,7 +1045,7 @@ class Query_Builder { { $sql = 'SELECT * FROM '.$this->quote_ident($table); $res = $this->query($sql); - return count($res->fetchAll()); + return (int) count($res->fetchAll()); } // -------------------------------------------------------------------------- @@ -1059,7 +1059,35 @@ class Query_Builder { */ public function count_all_results($table='') { - // @todo Implement count_all_results + // Set the table + if ( ! empty($table)) + { + $this->from($table); + } + + $sql = $this->_compile(); + + // Do prepared statements for anything involving a "where" clause + if ( ! empty($this->query_map)) + { + $result = $this->prepare_execute($sql, $this->values); + } + else + { + // Otherwise, a simple query will do. + $result = $this->query($sql); + } + + // Reset for next query + $this->_reset(); + + $rows = $result->fetchAll(); + $count = count($rows); + + // Unset rows to save memory + $rows = NULL; + + return (int) $count; } // -------------------------------------------------------------------------- diff --git a/tests/core/db_qb_test.php b/tests/core/db_qb_test.php index 28ea6e3..8bb51db 100644 --- a/tests/core/db_qb_test.php +++ b/tests/core/db_qb_test.php @@ -307,6 +307,28 @@ abstract class QBTest extends UnitTestCase { $this->assertTrue(is_numeric($query)); } + function TestCountAllResults() + { + if (empty($this->db)) return; + $query = $this->db->count_all_results('create_test'); + + $this->assertTrue(is_numeric($query)); + } + + function TestCountAllResults2() + { + if (empty($this->db)) return; + + $query = $this->db->select('id, key as k, val') + ->from('create_test') + ->where(' id ', 1) + ->or_where('key >', 0) + ->limit(2, 1) + ->count_all_results(); + + $this->assertTrue(is_numeric($query)); + } + } // End of db_qb_test.php \ No newline at end of file diff --git a/tests/db_files/FB_TEST_DB.FDB b/tests/db_files/FB_TEST_DB.FDB index 3f49ff6..9d4bfa6 100644 Binary files a/tests/db_files/FB_TEST_DB.FDB and b/tests/db_files/FB_TEST_DB.FDB differ