CodeIgniter - returns only one row?

At the moment, if I make a query in the database that should only return one row using:

...query stuff... $query = $this->db->get(); $ret = $query->result(); return $ret[0]->campaign_id; 

Is there a CodeIgniter function to return the first line? something like $query->row();

Or it would be even better if, if there was only one line, just use the request object directly.

eg. $query->campaign_id;

+55
database codeigniter
Nov 25 '10 at 7:15
source share
6 answers

You just answered your question :) You can do something like this:

 $query = $this->db->get(); $ret = $query->row(); return $ret->campaign_id; 

You can read more about this here: http://www.codeigniter.com/user_guide/database/results.html

+91
Nov 25 '10 at 19:36
source share

This is the best way, since it gives the result in one line:

 $this->db->query("Your query")->row()->campaign_id; 
+23
Dec 20
source share

To add to what Alisson said, you can check if the row will return.

 // Query stuff ... $query = $this->db->get(); if ($query->num_rows() > 0) { $row = $query->row(); return $row->campaign_id; } return null; // or whatever value you want to return for no rows found 
+11
Nov 25 '10 at 20:03
source share

To make the code clean that you want the first line, CodeIgniter now allows you to use:

 if ($query->num_rows() > 0) { return $query->first_row(); } 

Get the first row.

+4
Jan 08 '14 at 9:38
source share
 $this->db->get()->row()->campaign_id; 
+2
Oct 17 '16 at 17:25
source share

Change only two lines, and you actually get what you want.

 $query = $this->db->get(); $ret = $query->row(); return $ret->campaign_id; 

try it.

+1
Mar 03 '15 at 10:39
source share



All Articles