通过php打印SQL结果

时间:2013-12-07 08:15:03

标签: php sql

我正在尝试SUM 2列,然后减去差异。在SQL中,以下代码输出正确的响应。

但是我不确定如何通过php打印...

SQL - 代码:

SELECT budget_id, SUM( Amount ) - SUM( Expenditure ) AS diff FROM budget

这是我的php代码......

PHP - 代码:

                    $sql = "SELECT budget_id, SUM( Amount ) - SUM( Expenditure ) AS  diff FROM budget";

                  $result = mysql_query($sql) or die (mysql_error());

                  print "$".$result;
                  ?>

任何想法都会受到赞赏。

2 个答案:

答案 0 :(得分:0)

如评论中所述,您可以使用mysql_fetch_array

$sql = "SELECT budget_id, SUM( Amount ) - SUM( Expenditure ) 
AS  diff FROM budget";
              $result1 = mysql_query($sql) or die (mysql_error());
              while ($result=mysql_fetch_array($result1))
              {
              print_r($result);// to see the contents of the array
              echo $result[budget_id];
              echo $result[diff];
              }

不要使用mysql _ * ,因为它们已被删除。

答案 1 :(得分:0)

返回mysql_query是一个结果资源,你可以用这段代码迭代:

// fetch each row of the result as an associative array
while ($row = mysql_fetch_assoc($result)) 
{
    print $row['diff'] . "\n";
}

但请记住,自PHP 5.5起,PHP中的mysql_ *函数已被弃用,并将在以后的版本中删除。而是使用PDO