【问题标题】:Return only single record on codeigniter在 codeigniter 上只返回一条记录
【发布时间】:2016-03-16 13:53:23
【问题描述】:

我如何才能在此语句中只返回 1 条记录?

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

它给了我所有的记录

【问题讨论】:

  • 添加$this-&gt;db-&gt;select('column_name');并使用-&gt;row()获取单条记录
  • 你想返回什么值???
  • 我的意思是单个记录而不是单个值。我想使用它的 id 获得商品的名称、描述和价格
  • 您拥有多个具有相同 id 的商品??

标签: php database codeigniter


【解决方案1】:

使用$this-&gt;db-&gt;limit(1); 仅获取 1 条记录。

【讨论】:

    【解决方案2】:

    要获取单行表格,请使用-&gt;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

    【讨论】:

      【解决方案3】:

      使用这些

      方法01 - $this-&gt;db-&gt;get()

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

      方法02 - $this-&gt;db-&gt;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 循环中它总是会返回一个

      【讨论】:

        【解决方案4】:

        使用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() 的结果分配给变量,以便以后重复使用。

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

        【讨论】:

          【解决方案5】:

          使用这个:

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

          codeigniter 用户指南中提到了上面的代码。最好的一点是无需循环 foreach 即可获得非常具体的行值。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-27
            • 2016-05-22
            • 2018-09-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多