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 !

4

1 回答 1

15

尝试这样的事情:

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

或者,如果您只需要价格:

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

编辑

您的方法在某种程度上还可以,请看:

$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'];// 我们有一个对象,而不是数组,所以我们需要:

echo $row->cost_price;

或者,如果你想要一个数组,你可以使用result_array()而不是result().

我的方式 ,row()只返回第一行。它也是一个对象,如果你需要一个数组,你可以使用row_array().

我建议您在此处阅读有关所有内容的更多信息。

于 2013-06-04T21:14:10.433 回答