Reputation: 227
I have been trying to show a summaries of a column with the SUM() function in PHP.
I'm using $pointsummary= "SELECT SUM(points) FROM result WHERE id=$val";
to call my SUM function but i cant show it in my PHP. I've tried $test = mysqli_fetch_array($pointsummary);
and then echo $test[0];
but it wont work.
When i do this i get:
mysqli_fetch_array() expects parameter 1 to be mysqli_result
What should i do?
Upvotes: 3
Views: 246
Reputation: 2970
Your error is caused by the fact that $pointsummary
is a string and not a mysqli_result object. you need to use mysqli_query
first and use what that returns. eg.
$resultObj = mysqli_query($con, $pointsummary); // <--- $con is what you got from mysqli_connect()
$resultArr = mysqli_fetch_array($resultObj);
Another note is that with SELECT SUM(points) FROM result
i would suggest aliasing SUM(points)
with a name you'll recognize so that instead of having to var_dump the key/values of the mysqli_fetch_array
to find what the array key is for SUM(points)
you'll know before hand.
to do this use AS
. ie
SELECT SUM(points) AS `summary` FROM result
Upvotes: 8
Reputation: 94662
@Memor-X answer is good but I have a feeling that you have missed at least one step in the normal flow of event when querying a database in PHP using mysqli_
// 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'];
Upvotes: 2