只返回一行?

目前,如果我正在对数据库进行查询,而这个查询应该只返回一行,则使用:

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

是否有一个 CodeIgniter 函数来返回第一行? 就像 $query->row();

或者更好的是,如果只有一行, 直接使用查询对象。

例如 $query->campaign_id;

262876 次浏览

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

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

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

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

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.

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.

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

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;
}

}

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

If you require to get only one record from database table using codeigniter query then you can do it using row(). we can easily return one row from database in codeigniter.

$data = $this->db->get("items")->row();

You can do like this

$q  = $this->db->get()->row();


return $q->campaign_id;

Documentation : http://www.codeigniter.com/user_guide/database/results.html

Option 1 $limit = 1 $offset = 0

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

Option 2

$this->db->get("items")->row();