我正在尝试从数据库表中获取列的总和。但我得到的只是0.00。我的代码是:
$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");
$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_NUM);
echo $total_income = $total[0];
它应该回应306700.80。我检查了查询。它在数据库中工作正常,但在我的PHP脚本中没有。它有什么问题?
答案 0 :(得分:1)
编辑:我认为我的解释是错误的。但是仍然没有重新格式化数据库中的日期。 那就是:我想你将日期存储在DATE / DATETIME
类型的列中<?php
$total_income_query = $db->prepare("
SELECT SUM(credit)
from accounts
WHERE date BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y')
AND STR_TO_DATE(:endDate, '%d/%m/%Y')");
$stmt->bindParam(':startDate',$startDate);
$stmt->bindParam(':endDate',$endDate);
$stmt->execute();
$total = $stmt->fetch(PDO::FETCH_NUM);
echo $total_income = $total[0];
答案 1 :(得分:0)
好的,问题在于我的PDO代码。我应该写$ total_income_query而不是$ stmt。代码应如下所示......
$total_income_query = $db->prepare("select sum(credit) from accounts WHERE STR_TO_DATE(date, '%d/%m/%Y') BETWEEN STR_TO_DATE(:startDate, '%d/%m/%Y') AND STR_TO_DATE(:endDate, '%d/%m/%Y')");
$total_income_query->bindParam(':startDate',$startDate);
$total_income_query->bindParam(':endDate',$endDate);
$total_income_query->execute();
$total = $total_income_query->fetch(PDO::FETCH_NUM);
echo $total_income = $total[0];