本文介绍了在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;
推荐答案
Gah,请使用参数绑定!另外,对于单行/单列结果, 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!