dongtang6775 2014-07-21 21:43
浏览 149
已采纳

在PDO中获取SUM

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

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

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;
  • 写回答

2条回答 默认 最新

  • dougu3988 2014-07-21 21:48
    关注

    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();
    

    Addendum

    When developing, always run your PHP environment with full error disclosure. Then you won't miss easy mistakes like in your code above. In php.ini

    display_errors = On
    error_reporting = E_ALL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部