It's useful to count the number of results returned—often bugs can arise if a section of code which expects to have at least one row is passed zero rows. Without handling the eventuality of a zero result, an application may become unpredictably unstable and may give away hints to a malicious user about the architecture of the app. Ensuring correct handling of zero results is what we're going to focus on here.
$this->load->model('Some_model'), $data['num_results'] = $this->Some_model->some_model_function(); $this->load->view('some_view', $data);
function some_model_function() { $this->db->from('table'), return $num_rows = $this->db->count_all_results(); }
if (isset($num_results)) { echo 'There are ' . $num_results . ' returned'; }
This is fairly similar to the recipe above
num_rows()
, but there are a few key differences. We start off by calling a controller that loads the required model and calls a function within it. Take a look at the code in bold: $this->db->count_all_results();
. This will return the number of results returned in a given query. The result of this code is stored in an array and passed to a view where we test whether the variable $num_results
is set; if it is, we echo a brief message indicating the number of results.
18.222.239.77