Say I have a database table with three columns: ID, Name, and Age. I need to find the user with a specific (unique) ID, and then return the age. Currently, I am using the following code
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
How do I go about getting the age for this user? I think I have to use
$q->result()
But not sure how to use it with one row.
This question is related to
php
sql
codeigniter
you can use row() instead of result().
$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();
You simply use this in one row.
$query = $this->db->get_where('mytable',array('id'=>'3'));
Accessing a single row
//Result as an Object
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
echo $result->age;
//Result as an Array
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
echo $result['age'];
Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:
$this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));
return $query->row_array();
This will return a specific row based on your the set session data of user.
Source: Stackoverflow.com