Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter number of rows in controller

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?

like image 230
ahmedsaber111 Avatar asked Feb 21 '23 02:02

ahmedsaber111


1 Answers

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']);
like image 191
sankari Avatar answered Mar 05 '23 17:03

sankari