Number of rows in a Codeigniter controller

I have a model where I select the correct data from the database, as shown below:

<?php class vacancies extends CI_Model{ function vacancies() { $query = $this->db->query("SELECT * FROM ecc_vacancies_vac WHERE active_vac = 1 AND end_vac >= CURDATE() ORDER BY date_vac DESC"); if($query->num_rows() >= 1){ foreach($query->result() as $row){ $data[] = $row; } return $data; } } } 

and a controller for processing this data before sending it for viewing, as shown below:

 function index() { //check if there any available vacancies $this->load->model('vacancies'); $data['vacancies'] = $this->vacancies->vacancies(); // then i load the views here } 

What I need to do is find out the total number of rows returned here in the controller so that I can send the number to the view so that I can use it later.

When using active entries, I used this line of code:

 $data['num_rows'] = $$data['vacancies']->num_rows(); 

How can I define it in my case?

+4
source share
4 answers

The number of rows (); only works if you are still working on your β€œrequest part” in your model. It refers to a database object. You have already returned the data. Try the following:

  $data['num_rows'] = count($data['vacancies']); 
+2
source

PHP to the rescue. Since your model method returns an array, you get the total number of rows by a simple call to count () .

So for example

 $this->load->model('vacancies'); $data['vacancies'] = $this->vacancies->vacancies(); $data['number_of_vacancies'] = count($data['vacancies']); 
+3
source

You are returning an array from the model, so in the controller you can use the PHP count () function:

 $data['num_rows'] = count($data['vacancies']); 

There is also a problem with your model, the function will not return an array if there are no results, which can cause problems if you later treat it as an array. You must add initialization for $ data before the if statement, and then always return even an empty array:

 function vacancies() { $query = $this->db->query("SELECT * FROM ecc_vacancies_vac WHERE active_vac = 1 AND end_vac >= CURDATE() ORDER BY date_vac DESC"); $data = array(); if ($query->num_rows() >= 1){ foreach ($query->result() as $row){ $data[] = $row; } } return $data; } 
+2
source

To help you:

 if($query->num_rows()!==0){ return $query->result_array(); }else{ return 0; } 

Return 0 and do an if else statement in the view

 if($result!=0){ // No results found }else{ // Do something } 
+1
source

All Articles