I would like to sum the column age as shown on the image below on my table but im not sure how to implement this. i know i would need to use select sum(age) from user but where do i put this?
I did the below:
if (isset($_POST['date1']) && isset($_POST['date2'])) {
$sql = "SELECT * FROM user WHERE signup_date BETWEEN '".$_POST['date1']."' AND '".$_POST['date2']."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$x = 0;
while ($row = mysqli_fetch_assoc($result)) {
$output = '<tr>
<td>'.++$x.'</td>
<td>'.$row["name"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["age"].'</td>
<td>'.$row["signup_date"].'</td>
</tr>';
echo $output;
}
2
Answers
you can run a separate query for get sum of age field. like this:
And if you don’t want to run a new query, change your code like this:
You can explore these two options:
1.) Whilst looping through your result, you can decide to sum the values of the ‘age’ column and display the total age value at the end of your while loop
2.) Write another query on your
signup_date
table that uses the SUM() SQL function to sum up the age columnHere we go…
Option One:
$ageTotal = 0;
while ($row = mysqli_fetch_assoc($result)) {
}
/*
You can access the total age from the $ageTotal variable.
*/
Option Two:
/*
You can access the total age from the $ageTotal variable.
*/