19

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.

zinking
  • 5,561
  • 5
  • 49
  • 81
Ayub
  • 879
  • 3
  • 8
  • 22
  • 1
    Possible duplicate of [CodeIgniter - return only one row?](http://stackoverflow.com/questions/4280235/codeigniter-return-only-one-row) – Shomz Mar 04 '16 at 23:37

5 Answers5

55

SOLUTION ONE

$this->db->where('id', '3');
// here we select every column of the table
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

SOLUTION TWO

// here we select just the age column
$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
$data = $q->result_array();

echo($data[0]['age']);

SOLUTION THREE

$this->db->select('age');
$this->db->where('id', '3');
$q = $this->db->get('my_users_table');
// if id is unique, we want to return just one row
$data = array_shift($q->result_array());

echo($data['age']);

SOLUTION FOUR (NO ACTIVE RECORD)

$q = $this->db->query('SELECT age FROM my_users_table WHERE id = ?',array(3));
$data = array_shift($q->result_array());
echo($data['age']);
Elvira Gandelman
  • 327
  • 1
  • 4
  • 14
Dalen
  • 8,856
  • 4
  • 47
  • 52
  • Thanks, it works :) Is there a more efficient way to do this though? – Ayub Dec 16 '11 at 23:21
  • perhaps for such an simple query plain SQL would be more straigh forward choice, anyway i think i doesn't change a lot between these 4 cases – Dalen Dec 16 '11 at 23:27
6

you can use row() instead of result().

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();
Doms
  • 61
  • 1
  • 1
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'];
mobby
  • 361
  • 4
  • 8
0

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.

-1

You simply use this in one row.

$query = $this->db->get_where('mytable',array('id'=>'3'));
Waseem shah
  • 400
  • 5
  • 13