用数据库值计算php

时间:2016-04-25 14:53:18

标签: php mysql pdo

我有一个包含这样产品的数据库:

+----+--------+-------+
| ID | Name   | Price |
+----+--------+-------+
| 1  | Burger | 3,96  |
+----+--------+-------+
| 2  | Fries  | 1,49  |
+----+--------+-------+

我从JS获取了一系列id到PHP脚本,现在我想在单个变量中得到总价。

我使用PDO方法来获取数据,但我只是将它们发送到我的JS。我如何在PHP中实际使用该数据呢?

    $get = $db->prepare("SELECT price FROM products WHERE id IN ('$idString')");
    $get->execute();
    $rows = $get->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($rows);

2 个答案:

答案 0 :(得分:2)

如果您想获得所有价格表的总和,您只需在查询中添加sum函数,如

$get = $db->prepare("SELECT sum(price) FROM products IN ('$idString')");
$get->execute();
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows)

希望这有帮助。

答案 1 :(得分:2)

如果您只需要总数(没有其余数据),您可以在SQL中执行此操作:

$get = $db->prepare("SELECT SUM(price) as total FROM products WHERE id IN ($idString)");
$get->execute();
$row = $get->fetch(PDO::FETCH_ASSOC);
echo $row['total'];

或者,您可以迭代行并生成总计:

$get = $db->prepare("SELECT price FROM products WHERE id IN ($idString)");
$get->execute();
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$total = 0;
foreach ($rows as $row) {
    $total += $row['price'];
}
echo $total;