Alexia
Alexia

Reputation: 83

How do i get the sum of a column with a result set?

How do I return the sum of all values in one column from a returned result? For example, I want to add up the weight in each row and return it as total weight?

$requested_Date = date("$pick_up_year/$pick_up_month/$pick_up_day");                
$sql= "SELECT users.user_id, users.user_first, users.user_phone, requests.req_id, weight FROM users INNER join requests on 
        users.user_id=requests.user_id where pick_up_date = '$requested_Date'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
echo "<table>";
echo "<tr>
        <th>Customer ID</th>
        <th>Customer Name</th>
        <th>Customer Phone Number</th>
        <th>Request ID</th>
        <th>Weight</th>
    </tr>";
if($resultCheck > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo'
    <tr>
        <th>'.$row['user_id'].'</th>
        <th>'.$row['user_first'].'</th>
        <th>'.$row['user_phone'].'</th>
        <th>'.$row['req_id'].'</th>
        <th>'.$row['weight'].'</th>';                           
    }

Upvotes: 1

Views: 41

Answers (1)

Joseph_J
Joseph_J

Reputation: 3669

Just add the weights in the loop.

$requested_Date = date("$pick_up_year/$pick_up_month/$pick_up_day");                
$sql= "SELECT users.user_id, users.user_first, users.user_phone, requests.req_id, weight FROM users INNER join requests on 
       users.user_id=requests.user_id where pick_up_date = '$requested_Date'";    
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
echo "<table>
    <tr>
        <th>Customer ID</th>
        <th>Customer Name</th>
        <th>Customer Phone Number</th>
        <th>Request ID</th>
        <th>Weight</th>
    </tr>";
if($resultCheck > 0){
    $totalWeight = 0;
    while($row = mysqli_fetch_assoc($result)){
        $totalWeight += $row['weight']; 
echo'<tr>
    <td>'.$row['user_id'].'</td>
    <td>'.$row['user_first'].'</td>
    <td>'.$row['user_phone'].'</td>
    <td>'.$row['req_id'].'</td>
    <td>'.$row['weight'].'</td>
</tr>';                          
}    
echo '</table>'.$totalWeight;

Upvotes: 1

Related Questions