class mysqli_result 的对象无法转换为数字 (PHP | MySQL)

Object of class mysqli_result could not be converted to number (PHP | MySQL)

如果这个问题重复或之前有人问过,我很抱歉。在网上看了一些资料,还是没看懂。

所以,我有一个 transaction table:

id customer qty date
1 cus1 5 2021-04-01
2 cus2 3 2021-04-01
3 cus3 7 2021-04-02

我想获取所有 qty 数据,其中 date = "2021-04-01",然后我想求和。所以,我使用以下代码:

$qty = $db->query("SELECT SUM(`qty`) FROM `transaction` WHERE `date` = '2021-04-01'");

Note: the $db variable is the connection function to the database

接下来,我要将查询结果相乘,如下:

$profit = $qty * 10;

当我 运行 代码时,我收到一条错误消息:

Notice: Object of class mysqli_result could not be converted to number

我该如何解决?我只想乘以变量 $qty ($qty * 10)

的查询结果

我是初学者。任何帮助将不胜感激。谢谢大家。

我更新了您的 SQL 查询以对聚合进行别名以便于访问。

$qty = $db->query("SELECT SUM(`qty`) as 'val_sum' FROM `transaction` WHERE `date` = '2021-04-01'");

您可以使用“(int) $string_value”将字符串转换为 int

if ($qty->num_rows > 0) {
   $row = $qty->fetch_assoc()
   $profit = (int) $row['val_sum'] * 10;
}