Categories: Snippets

Query in Codeigniter

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']);

you can use row() instead of result()

$this->db->where('id', '3');
$q = $this->db->get('my_users_table')->row();

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'];

 

Recent Posts

Sample Contact Form with validation, Captcha & Notification

Contact Controller [crayon-67a5af06915d0908881412/] Contact_form.php - view [crayon-67a5af06915db014597837/] Contact_model [crayon-67a5af06915e1380880137/] Captcha Helper [crayon-67a5af06915e8721640823/] Notifications_model [crayon-67a5af06915f0330063264/] Database…

6 years ago

Delete Files and Execute Database Query remotely

[crayon-67a5af06918ec234952682/] [crayon-67a5af06918f0212694733/]  

6 years ago

Random String Codeigniter

[crayon-67a5af069198f234502967/] The first parameter specifies the type of string, the second parameter specifies the length.…

6 years ago

Codeigniter Ajax Form Validation Example

Create Controller [crayon-67a5af0691a1c950893703/] 2. Create View File [crayon-67a5af0691a20891623591/]  

7 years ago

Codeigniter passing 2 arguments to callback – Email validation

[crayon-67a5af0691ae0379026335/] [crayon-67a5af0691ae2318830571/]  

7 years ago

Setting Error Messages

All of the native error messages are located in the following language file: system/language/english/form_validation_lang.php To set…

7 years ago