CodeIgniter : One record and count treatment
This post will treat the case of one record treatment and counting in active record through the CodeIgniter’ core. Suppose you are displaying a user’s profile. It’s good practice to store all database queries in the MODEL. I use this:
CONTROLLER:
$this->load->model('Profile'); $data['row'] = $this->Profile_model->profile_read(); //get profile data $this->load->view('profile_view', $data); //load data to view
MODEL:
function profile_read() { $this->db->where('user_id', $user_id); $query = $this->db->get('user_profiles'); //get all data from user_profiles table that belong to the respective user return $query->row(); //return the data }
In the model you can have all your other database functions (create, delete, update)
VIEW:
<?php echo $row->name; ?> <?php echo $row->email; ?> <?php echo $row->about; ?>
Finally in the view you can echo any rows from the table that belong to the user.
$query->row() just fetches the first row.
So instead of looping through the result, you could just do:
$student_id = $query->row()->student_id;
OR
$row = $query->row(); $student_id = $row->student_id;
Assuming the query will always return a row.
In the other case, the normal result parsing is :
$query = $this->db->query("YOUR QUERY"); foreach ($query->result() as $row) { echo $row->title; echo $row->name; echo $row->body; }
Difference between $query>num_rows() and $this->db->count_all_results()
There are two ways to count total number of records that the query will return. First this
$query = $this->db->query('select * from users');
return $query->num_rows();
This will return number of rows the query brought.
Second
return $this->db->count_all_results('select * from users');
Simply count_all_results will require to run the query again.
Cheers,