Reputation: 822
I have a model where I select the proper data from database as 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 to handle this data before sending to view as 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 to know the total number of returned rows here in the controller so I can send the number to the view to use it later.
When using active records I used to use this line of code:
$data['num_rows'] = $$data['vacancies']->num_rows();
How can I define it in my case?
Upvotes: 4
Views: 14187
Reputation: 140
To help you out:
if($query->num_rows()!==0){
return $query->result_array();
}else{
return 0;
}
Return 0 and make an if else statement in the view
if($result!=0){
// No results found
}else{
// Do something
}
Upvotes: 1
Reputation: 4044
You are returning an array from the model, so in the controller you can use PHP's count() function:
$data['num_rows'] = count($data['vacancies']);
There's also a problem with your model, the function will not return an array if there are no results, which could cause problems if you treat it like an array later on. You should add an 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;
}
Upvotes: 2
Reputation: 1907
The num-rows(); only works if you're still working on your "query part" in your model. It reffers to the DB object. You already returned the data. Try this:
$data['num_rows'] = count($data['vacancies']);
Upvotes: 2
Reputation: 476
PHP to the rescue. Since your model method returns an array, you get the total number rows by a simple count() call.
So, for example,
$this->load->model('vacancies');
$data['vacancies'] = $this->vacancies->vacancies();
$data['number_of_vacancies'] = count($data['vacancies']);
Upvotes: 3