How to get single result from mysql using code igniter?

Having problems with Codeigniter. I am trying to get the product value from mysql. The mysql table contains a field called cost_price . I am trying to get the result of a single product using the product identifier. The im code is used here,

 $query = $this->db->query('SELECT * FROM items WHERE id="$id"'); $row = $query->result(); echo $row['cost_price']; 

But nothing happens! What is the problem with my code?

I tried the wrong code to check if the database is responding or not, but it looks like the database is working fine. I can’t understand why my query cannot find any result!

+4
source share
1 answer

Try something like this:

 $row = $this->db->get_where('items', array('id' => $id))->row(); 

Or if you just need a price:

 $price = $this->db->select('cost_price') ->get_where('items', array('id' => $id)) ->row() ->cost_price; 

EDIT

Your method was fine to the point, look:

 $query = $this->db->query('SELECT * FROM items WHERE id="$id"'); $res = $query->result(); // this returns an object of all results $row = $res[0]; // get the first row 

echo $row['cost_price']; // we have an object, not an array, so we need:

 echo $row->cost_price; 

Alternatively, if you want an array, you can use result_array() instead of result() .

My path, row() , returns only the first row. It is also an object, and if you need an array, you can use row_array() .

I suggest you read about everything here .

+12
source

Source: https://habr.com/ru/post/1484505/


All Articles