将所有值一起添加到SQL SELECT中

时间:2016-02-25 17:58:30

标签: php mysql sql

如何将所有amounts添加到一起,以便返回所有单独的提款金额而不是此选择脚本返回其中一个数字全部加在一起?

<?php
$end_date = strtotime($nextdate);
$start_date = strtotime($statement_date);
$username = $usr['username'];
$result = mysql_query("SELECT * FROM `usr_withdraw` WHERE `timestamp` > '$start_date' AND `timestamp` < '$end_date' AND `username` = '$username'")or die(mysql_error());

while($balance = mysql_fetch_array( $result )) { 
    echo $balance['amount'];
}
?>

2 个答案:

答案 0 :(得分:1)

要仅返回包含所有金额总和的1行,请使用sql sum()函数。

SELECT sum(amount) FROM `usr_withdraw` WHERE ...

答案 1 :(得分:0)

待办事项

$result = mysql_query("SELECT SUM(amount) FROM `usr_withdraw` WHERE `timestamp` > '$start_date' AND `timestamp` < '$end_date' AND `username` = '$username'")or die(mysql_error());

但是请记住,这些mysql_ *函数是从版本7开始的PHP之外,那么你的代码很快就会过时了。理想的是使用mysqli_ *函数或PDO。