Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter $this->db->get(), how do I return values for a specific row?

Tags:

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.

like image 587
Ayub Avatar asked Dec 16 '11 23:12

Ayub


2 Answers

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']);
like image 188
Dalen Avatar answered Sep 18 '22 20:09

Dalen


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

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();
like image 27
Doms Avatar answered Sep 17 '22 20:09

Doms