Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch a single result from mysql using code igniter? [duplicate]

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 !

like image 536
Oritro Ahmed Avatar asked Jun 04 '13 21:06

Oritro Ahmed


1 Answers

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.

like image 156
Shomz Avatar answered Oct 25 '22 10:10

Shomz