在 PDO 中获取 SUM

Getting the SUM in PDO(在 PDO 中获取 SUM)
本文介绍了在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)