如何减去多个查询的值

时间:2013-10-08 15:57:31

标签: php mysql subtraction

我已经走了很长的路要走到最后一个问题。一切都是我的代码现在正在工作,但我无法得到这个最后的小问题。现在我有:

$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,但是现在我给了我所有列的第一个值。谢谢!

1 个答案:

答案 0 :(得分: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);

您可以在此处了解如何在http://www.php.net/manual/en/book.pdo.php

创建PDO个关联