使用Codeigniter遇到问题。我试图从mysql获取产品的价值。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()
。
我建议你在这里阅读更多关于这些的内容。