简体   繁体   中英

Return only single record on codeigniter

How can I return only 1 record on this statement?

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

It gives me all the records instead

For fetching single row form table use ->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>';
}

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

Use $this->db->limit(1); to get 1 record only.

Use these

Method 01 - $this->db->get()

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

Method 02 - $this->db->limit() in CI

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

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

These will only produce one set of data. and in your foreach loop it will always return one

Use limit , so sql will return you the only first row found, but not the whole set of rows. The CI's manual is explicit about getting results.

here're two one-liner solutions, through the 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;

if you need to reference several values later on, assign result of row() to variable, to re-use later.

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

Use this:

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

The code above is mentioned by the codeigniter user guide. The best about this is no need to loop foreach where you can get very specific row value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM