Counting the number of returned results with num_rows()

It's useful to count the number of results returned—often bugs can arise if a section of the code that expects to have at least one row is passed with 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.

How to do it...

  1. We're going to create a block of code for a model and controller. You may already have code in a controller, model, or view that does all or some of the following—obviously, you can skip any step that you do not need. Add or adapt the ensuing code into your controller:
    $this->load->model('Some_model'),
    $data['query'] = $this->Some_model->some_model_function();
    $this->load->view('some_view', $data);
  2. Add or adapt the following code into your model:
    function some_model_function() {	
           $query = $this->db->get('database_table_name'),
           return $query;
    }
  3. Add or adapt the following code into your view:
    if ($query->num_rows() > 0) {
      foreach ($query->result() as $row) {
        echo $row->item1;
        echo $row->item2;
      }
    } else {
      echo 'No results returned';
    }

How it works...

This is quite common; a controller loads the required model and calls a function within that model; the result of this model is stored in an array. This is then passed to a view. It is here in the view that we'd count the number of rows. Take a look at the line in bold. We're using the CodeIgniter function num_rows() to look into the $query result and count the number of rows returned by the model. We're asking whether the number of rows is greater than zero. If it is, there must be at least one result from the model—we then look through the $query array as we would normally. However, if the number of results isn't greater than zero, it would mean that there were no results returned by the model. So, we use an else statement to display a brief message stating that there were No results returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.34.87