在 PDO 中获取 SUM

2022-01-09 00:00:00 sum php pdo

下面是我的代码,由于某种原因,它没有给我 SUM.这总是返回 0.为什么它不起作用?

Below is my code and for some reason it's not giving me the SUM. This always returns 0. Why doesn't it work?

我使用 if ($totSubmits==''){ 来避免我的数据库中出现空白字段.

I've used if ($totSubmits==''){ to avoid blank fields in my database.

我也尝试删除 AS due_fees 并使用 $dueAmont = $result[0],但没有运气.

I also tried removing AS due_fees and using $dueAmont = $result[0], but no luck though.

$sql= "SELECT SUM(dueFees) AS due_fees FROM coursePayments WHERE studentId = $student"; 
$stmt = $c->prepare($sql);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);
$dueAmont = $result['due_fees']; 
if ($dueAmont==""){
    $dueAmont = '0';
}
echo $student." due amount ".$dueAmont;

推荐答案

哎呀,使用参数绑定!此外,fetchColumn() 对于单行来说非常简单/单列结果

Gah, use parameter binding! Also, fetchColumn() is nice and easy for single row / single column results

$sql= "SELECT SUM(dueFees) FROM coursePayments WHERE studentId = ?"; 
$stmt = $c->prepare($sql);
$stmt->execute(array($student));
$dueAmont = (int) $stmt->fetchColumn();

附录

在开发时,始终运行您的 PHP 环境,并显示完整的错误信息.然后你就不会错过上面代码中的简单错误.在 php.ini

display_errors = On
error_reporting = E_ALL

相关文章