5

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 !

Oritro Ahmed
  • 118
  • 1
  • 2
  • 10
  • echo out your $query, does it look normal ? – Drew Jun 04 '13 at 21:10
  • Frankly speaking i am not familiar with CI. i don't even know how this DB Query class work. I just find some answer in their DOC and used it. but not working ! – Oritro Ahmed Jun 04 '13 at 21:14
  • The problem with your original query is that you put a variable reference ($id) inside a single-quoted phrase. PHP does not convert '$id' to the value. If you put variables inside a quoted phrase, use double quotes on the outside. For further clarity, wrap your variables in {braces}. For example: `$query = $this->db->query("SELECT * FROM items WHERE id={$id}");` – pbarney Feb 12 '16 at 21:36

1 Answers1

15

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

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 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.

Shomz
  • 37,421
  • 4
  • 57
  • 85