2012-12-14 82 views
0

我想用mysql_fetch_array时使用MySQL表格来计算total price。 但是,当我回声total,我得到的计算总价步骤:使用mysql_fetch_array时防止多重回显

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; 

} 

} 

如何计算从数据库总价没有额外的两行呢?

+0

将回声移到循环的外部。 –

回答

3

首先...如果你只需要求和使它像这样:

$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; 
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; 
1

只需使用一个总和?

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