CodeIgniter - return only one row?

2019-01-08 16:12发布

问题:

At the moment if I am doing a query on 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 row? something like $query->row();

Or even better would be the ability to, if there was only one row, to just use the query object directly.

e.g. $query->campaign_id;

回答1:

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

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

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



回答2:

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;


回答3:

To add on to what Alisson said you could check to see if a row is returned.

// 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


回答4:

To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:

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

To retrieve the first row.



回答5:

$this->db->get()->row()->campaign_id;


回答6:

Change only in two line and you are getting actually what you want.

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

try it.



回答7:

We can get a single using limit in query

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);


回答8:

class receipt_model extends CI_Model {

   public function index(){

      $this->db->select('*');

      $this->db->from('donor_details');

      $this->db->order_by('donor_id','desc');

      $query=$this->db->get();

      $row=$query->row();

      return $row;
 }

}