[英]How to get a single value from one record from a query into a field
In my system, I have plenty of instances of code like the following:在我的系统中,我有很多代码实例,如下所示:
$value = mysqli_fetch_array(mysqli_query($con, "SELECT SUM(price) as total from items WHERE a=1 AND b=2"));
Then $value
is used later in the code and has the total price calculated from the array然后在代码中稍后使用$value
并从数组中计算出总价格
I'm trying to replicate this in a new piece of code as follows:我正在尝试在一段新代码中复制它,如下所示:
$recent_sale_id = mysqli_fetch_array(mysqli_query($con, "SELECT id as id FROM items where item_code='$item_code' and status='BULK-ITEM-SALE' order by sold_at DESC LIMIT 1"));
The query works when run directly against the database (of course replacing $item_code with the item code).该查询在直接针对数据库运行时有效(当然用项目代码替换 $item_code)。 But $recent_sale_id
then just has the value 'Array'.但是$recent_sale_id
然后只有值 'Array'。
I'm wondering two things:我想知道两件事:
What am I doing wrong?我究竟做错了什么? My code seems to be exactly the same as the other code that works correctly.我的代码似乎与其他正常工作的代码完全相同。
Is there a simpler way to get a value from a query into a field, without using a function that seems like it will create an array?是否有一种更简单的方法可以将查询中的值获取到字段中,而不使用看起来会创建数组的函数? Is there a more suitable mysqli_fetch*
function?有没有更合适的mysqli_fetch*
函数?
There's no way you could access $value
as a number because it is also an array.您无法将$value
作为数字访问,因为它也是一个数组。 In the first case you would need to use either $value[0]
or $value['total']
to get the result;在第一种情况下,您需要使用$value[0]
或$value['total']
来获得结果; in the second either $recent_sale_id[0]
or $recent_sale_id['id']
.在第二个$recent_sale_id[0]
或$recent_sale_id['id']
。 You can use either form because mysqli_fetch_array
by default returns arrays indexed both by column number and column name.您可以使用任何一种形式,因为默认情况下mysqli_fetch_array
返回按列号和列名索引的数组。
Unfortunately the MySQLi interface does not have an equivalent to PDO's fetchColumn
which allows you to directly fetch the value of a single column from a row in a result set.不幸的是,MySQLi 接口没有与 PDO 的fetchColumn
等效的fetchColumn
,它允许您直接从结果集中的行中获取单个列的值。
If $recent_sale_id is returning a array in this case, that means it is of array type and in terms of getting data from mysql query often it comes in array format though you have added a limit 1.如果 $recent_sale_id 在这种情况下返回一个数组,则意味着它是数组类型,并且就从 mysql 查询获取数据而言,它通常采用数组格式,尽管您添加了限制 1。
One thing you can do to get the value is try $recent_sale_id[0] for the actual output.您可以做的一件事是尝试$recent_sale_id[0]以获得实际输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.