在 PDO 中获取 SUM [英] Getting the SUM in PDO

查看:22
本文介绍了在 PDO 中获取 SUM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码,由于某种原因,它没有给我 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

这篇关于在 PDO 中获取 SUM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆