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:


$data['row'] = $this->Profile_model->profile_read(); //get profile data
$this->load->view('profile_view', $data); //load data to view


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)


<?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;


$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.


return $this->db->count_all_results('select * from users');

Simply count_all_results will require to run the query again.



Since 30 years I work on Database Architecture and data migration protocols. I am also a consultant in Web content management solutions and medias protecting solutions. I am experienced web-developer with over 10 years developing PHP/MySQL, C#, VB.Net applications ranging from simple web sites to extensive web-based business applications. Besides my work, I like to work freelance only on some wordpress projects because it is relaxing and delightful CMS for me. When not working, I like to dance salsa and swing and to have fun with my little family.

You may also like...