2012-12-14 52 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...