Having trouble with Codeigniter. I am trying to fetch the value of a product from mysql. The mysql table contain a field called cost_price
. I am trying to fetch the result of a single product using the product ID. Here is the code im using,
$query = $this->db->query('SELECT * FROM items WHERE id="$id"');
$row = $query->result();
echo $row['cost_price'];
But nothing is happening ! What is the problem with my code?
I tried some wrong code to check whether the database is responding or not, but it seems that the database is working fine. Can't understand why my query can't find any result !
Try something like this:
$row = $this->db->get_where('items', array('id' => $id))->row();
Or, if you just need the price:
$price = $this->db->select('cost_price')
->get_where('items', array('id' => $id))
->row()
->cost_price;
EDIT
Your method was ok up to a 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
// we have an object, not an array, so we need:echo $row['cost_price'];
echo $row->cost_price;
Alternatively, if you want an array, you can use result_array()
instead of result()
.
My way, row()
, returns only the first row. It's also an object, and if you need an array, you can use row_array()
.
I suggest you read more about all that here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With