在使用 Codeigniter 时遇到问题。我正在尝试从 mysql 中获取产品的值(value)。 mysql 表包含一个名为 cost_price
的字段。我正在尝试使用产品 ID 获取单个产品的结果。这是我使用的代码,
$query = $this->db->query('SELECT * FROM items WHERE id="$id"');
$row = $query->result();
echo $row['cost_price'];
但是什么也没有发生!我的代码有什么问题?
我尝试了一些错误的代码来检查数据库是否响应,但看起来数据库工作正常。不明白为什么我的查询找不到任何结果!
尝试这样的事情:
$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()
。
我建议您阅读更多有关所有内容的信息 here .