php 如何使用代码点火器从 mysql 获取单个结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16927499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:53:40  来源:igfitidea点击:

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

phpmysqlcodeigniter

提问by Oritro Ahmed

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,

Codeigniter 有问题。我正在尝试从 mysql 中获取产品的价值。mysql 表包含一个名为cost_price. 我正在尝试使用产品 ID 获取单个产品的结果。这是我使用的代码,

$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 !

我尝试了一些错误的代码来检查数据库是否有响应,但似乎数据库工作正常。不明白为什么我的查询找不到任何结果!

回答by Shomz

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

echo $row->cost_price;

Alternatively, if you want an array, you can use result_array()instead of result().

或者,如果你想要一个数组,你可以使用result_array()而不是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().

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

I suggest you read more about all that here.

我建议你在这里阅读更多关于这一切的信息