如何在PHP中显示SUM列

时间:2015-12-08 22:13:04

标签: php mysql

我一直在尝试用PHP中的SUM()函数显示列的摘要。

我使用$pointsummary= "SELECT SUM(points) FROM result WHERE id=$val";调用我的SUM函数,但我无法在PHP中显示它。我已经尝试了$test = mysqli_fetch_array($pointsummary);然后回复了$test[0];但它无法正常工作。 当我这样做时,我得到:

  

mysqli_fetch_array()期望参数1为mysqli_result

我该怎么办?

2 个答案:

答案 0 :(得分:8)

您的错误是由$pointsummary是字符串而不是mysqli_result对象引起的。您需要先使用mysqli_query并使用返回的内容。例如

$resultObj = mysqli_query($con, $pointsummary); // <--- $con is what you got from mysqli_connect()
$resultArr = mysqli_fetch_array($resultObj);

另一个注意事项是,对于SELECT SUM(points) FROM result,我建议使用您将识别的名称对SUM(points)进行别名,以便不必使用var_dump mysqli_fetch_array的键/值来查找内容数组键是用于SUM(points)的,你手头就知道了。

使用AS来执行此操作。即

SELECT SUM(points) AS `summary` FROM result

答案 1 :(得分:2)

@ Memor-X答案很好但我觉得你在使用mysqli_

在PHP中查询数据库时,至少错过了正常事件流程中的一步
// create a query as a text string
$pointsummary = "SELECT SUM(points) as `tot_points` 
                 FROM result 
                 WHERE id=$val";

// issue the query to the MySQL Server for execution
// this should create a result set as long as the query is valid
$result = mysqli_query($con, $pointsummary);

// Check that the query had no errors
if ( ! $result ) {
    echo mysqli_error($con);
    exit;
}

// request the first row from the result set
// as we know this query will only return one row
// we dont need to do this in a loop
$row = mysqli_fetch_assoc($result);

echo $row['tot_points'];