使用mysql_fetch_array时防止多重回声

时间:2012-12-14 14:04:33

标签: php mysql

我想在使用total price时使用MySQL表计算mysql_fetch_array。 但当我回复total时,我会逐步得到计算出的总价格:

5000
10000
16000

相反,我想得到最终结果。

这是我的PHP代码:

$year=$_PoST['year'];
$mounth=$_POST['mounth'];

$con=mysql_connect('localhost','root','');
$select=mysql_select_db('payment');
$sql='select * from payments p 
where year(p.date) = '.$year.' and monthname(p.date) = "'.$mounth.'"';
$query=mysql_query($sql);
while($row=mysql_fetch_array($query)){
$price=$row['full_amount_must_pay'] ;

$total=$price+$total;
echo $total;

}

}

如何在没有额外两行的情况下计算数据库的总价格?

3 个答案:

答案 0 :(得分:3)

首先......如果你只需要Sum就像这样:

$sql='select SUM(full_amount_must_pay) from payments p where year(p.date) = '.$year.' and monthname(p.date) = "'.$mounth.'"';
$query=mysql_query($sql);
if($row=mysql_fetch_array($query)){
    echo $row[0];
}

否则打印你的总时间......就像这样

while($row=mysql_fetch_array($query)){
    $price=$row['full_amount_must_pay'] ;
    $total=$price+$total;
}
echo $total;

答案 1 :(得分:1)

只需使用一笔钱?

select sum(full_amount_must_pay) from payments p
where year...

答案 2 :(得分:0)

使用

$year=$_PoST['year'];
$mounth=$_POST['mounth'];

    $con=mysql_connect('localhost','root','');
    $select=mysql_select_db('payment');
    $sql='select * from payments p 
    where year(p.date) = '.$year.' and monthname(p.date) = "'.$mounth.'"';
    $query=mysql_query($sql);
    while($row=mysql_fetch_array($query)){
    $price=$row['full_amount_must_pay'] ;

    $total=$price+$total;


    }
    echo $total;