获取列的总和

时间:2019-06-20 12:37:35

标签: php mysql sql pdo

试图获取“交易”表中(总计)列的总和,其中type =“ outbound”,但我无法打印出来。

https://graph.microsoft.com/v1.0/deviceManagement/managedDevices?$filter=managementAgent ne 'eas'&$select=managementAgent

我收到此错误

  

(..)中的数组到字符串的转换

如何回显总列的总和?

2 个答案:

答案 0 :(得分:2)

一旦获取了结果集,就会得到一个结果数组-无法将其打印为echo中的值。您需要选择要打印的确切列。如果您通过执行SUM(total) AS tot为别名分配别名,则更容易-现在总和的名称为tot

还要在准备好的语句中使用适当的有界参数。

$stmt4 = $dbcon->prepare("SELECT SUM(total) as tot FROM transactions WHERE proid=?");
$stmt4->execute([$id]);
$thetotal = $stmt4->fetch(PDO::FETCH_ASSOC);

echo $thetotal['tot'];

答案 1 :(得分:0)

警告切勿将PHP变量放在SQL字符串中。它使您的SQL容易受到SQL注入的攻击,并可能导致许多问题。

您可以使用fetchColumn

解决问题
$stmt4 = $dbcon->prepare("SELECT SUM(total) FROM transactions WHERE proid=? ");
$stmt4->execute([$id]);
$thetotal = $stmt4->fetchColumn();

echo $thetotal;

或者您可以将fetchPDO::FETCH_COLUMN一起使用

$stmt4 = $dbcon->prepare("SELECT SUM(total) FROM transactions WHERE proid=? ");
$stmt4->execute([$id]);
$thetotal = $stmt4->fetch(PDO::FETCH_COLUMN);

echo $thetotal;