2016-03-16 68 views
1

如何在此声明中只返回1条记录?仅在codeigniter上返回单个记录

public function edititem($id){ 
    $this->db->select('*'); 
    $query = $this->db->get('tblitem'); 
    $this->db->where('item_id',$id); 

    foreach ($query->result() as $row){ 
     echo $row->item_id.'</br>'; 
     echo $row->item_name.'</br>'; 
     echo $row->item_description.'</br>'; 
     echo $row->item_price.'</br>'; 
    } 
} 

它给我的所有记录,而不是

+0

只需添加'$ this-> db-> select('column_name');'并使用' - > row()'获取单个记录 – Saty

+0

您将返回哪个单值? – Saty

+0

我的意思是单个记录不是单个值。我想要使​​用其编号的商品的名称,说明和价格 – aronccs

回答

0

使用$this->db->limit(1);只得到1分的纪录。

+1

正是我需要的,谢谢! – aronccs

0

使用这些

方法01 - $this->db->get()

$query = $this->db->get('tblitem' ,1 , 0); # Set Limit 

方法02 - $this->db->limit() in CI

$this->db->limit(1); 

方法03 - Result Rows in CI

$row = $query->first_row('array'); 
$row = $query->last_row('array'); 
$row = $query->next_row('array'); 
$row = $query->previous_row('array'); 

这些只会产生一组数据。并在foreach循环后总是回到一个

1

有关读取单行形式表使用->row()

function edititem($id) { 
    $this->db->select('item_id,item_name, item_description,item_price'); 
    $this->db->where('item_id', $id); 
    $this->db->limit(1);// only apply if you have more than same id in your table othre wise comment this line 
    $query = $this->db->get('tblitem'); 
    $row = $query->row(); 

    echo $row->item_id . '</br>'; 
    echo $row->item_name . '</br>'; 
    echo $row->item_description . '</br>'; 
    echo $row->item_price . '</br>'; 
} 

https://www.codeigniter.com/userguide3/database/results.html

0

使用limit,因此SQL将返回只有第一行发现,但不是整组的行。关于获得结果的CI's manual is explicit

我这里还有两个一班轮解决方案,通过get()

// ... other query conditions 
$this->db->limit(1)->get('tblitem')->row()->your_key; 

// or with the short syntax for defining limit, through the get: 
$this->db->get('tblitem', 1, 0)->row()->your_key; 
如果您稍后需要参考的几个值,分配行()变量的结果

,以后再使用。

$row = $this->db->limit(1)->get('tblitem')->row(); 
0
使用

此:

$this->db->get()->custom_row_object(0, 'Your_Model'); 

上面的代码是由笨用户指南中提到的。最好的方面是无需循环foreach,您可以获得非常具体的行值。

相关问题