Displaying "Sum()" in php – PHP

  php

Q(Question):

Hello… total newb here… I know how to achieve a "sum" by using the following statement:
SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;

but… I don’t know how to display the result? I realize the "AS" is the column header for the answer but I don’t know how to echo it.

All help is appreciated.

Thank you!

A(Answer):

How do you currently echo a field that isn’t a sum?

A(Answer):

usually by assigning a variable and echoing the variable. But I can’t find any examples where the "Sum()" function is used in a variable. And as mentioned before.. I’m new.

A(Answer):

Please post the code you use when it’s not a sum.

A(Answer):

Something like this…

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

A(Answer):

Please use code tags when posting code or formatted data.

So given your query above, on line 20 instead of something like $row["id"], use $row["TotalItemsOrdered"]

A(Answer):

That worked. Thank you.

LEAVE A COMMENT