2013-10-08 89 views
0

我有很長的路要走到最後一個問題。一切都是我的代碼現在正在工作,但我無法得到這最後一個小問題。現在我有:如何減去多個查詢的值

$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS 
value_sum FROM maindata GROUP BY phonenumber, dataplan"; 


$result = mysql_query($sql); 
$row = mysql_fetch_assoc($result); 
$val = $row["value_sum"]; 
$plan = $row["currentplan"]; 
$remain = $plan - $val; 


if (!$result) { 
    echo "Could not successfully run query ($sql) from DB: " . mysql_error(); 
    exit; 
} 

if (mysql_num_rows($result) == 0) { 
    echo "No rows found, nothing to print so am exiting"; 
    exit; 
} 

它只是減去第一個值而不是所有的值。顯示如下:

while ($row = mysql_fetch_assoc($result)){ 
echo "<tr>"; 
echo "<td>".$row['phonenumber'] . "</td> "; 
echo "<td>".$row['currentplan'] . "</td> "; 
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> "; 
echo "<td>".$remain . " MB</td> "; 
echo "<td>".$row['email'] . "</td></tr>"; 
} 

所以我的目標是從所有dataplans減去所有value_sums,但我現在所擁有的,讓我對所有列的第一個值。謝謝!

回答

0

mysql_fetch_assoc()將始終獲得一行。您可以在循環中使用它,或者更好地使用PDO,例如。像這樣:

$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS 
     value_sum FROM maindata GROUP BY phonenumber, dataplan"; 
$results = $pdo->query($sql); 

你可以閱讀在這裏創建PDO連接http://www.php.net/manual/en/book.pdo.php