blerta blerta - 3 months ago 9
PHP Question

total sum of a row

I have this query which gives me the transactions for a user, and the output is a table with the information. There is this row named

basket_value
which contains some numbers, and I need to get the sum of those numbers. Could you please help me?

$query3 = 'SELECT users.first_name,users.last_name,users.phone,
retailer.date, SUM(retailer.basket_value),
retailer.time,retailer.location,retailer.type_of_payment
FROM users ,retailer
WHERE users.user_id="'.$id_user.'"
AND users.user_id=retailer.user_id GROUP BY users.user_id';

$result3 = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result3)) {
echo "Total ". $row['user_id']. " = $". $row['SUM(basket_value)'];
echo "<br />";
}

Answer

I suppose that also your query have some problem and suppose that you have an id to retrieve users, I would do in that way

$query3 = 'SELECT users.user_id,users.first_name,users.last_name,
                  users.phone, retailer.date, 
                  SUM(retailer.basket_value) as total_sum,
                  retailer.time,retailer.location,retailer.type_of_payment
           FROM users ,retailer WHERE users.user_id="'.$id_user.'"
           AND users.user_id=retailer.user_id
           GROUP BY users.user_id,users.first_name,users.last_name,
                    users.phone, retailer.date,retailer.time,retailer.location,
                    retailer.type_of_payment '

$result = $mysqli->query($query3);

Now if you want the sum for each user:

while ($row = $result->fetch_row()) {
        echo "Player: ".$row['user_id']." total: ".$row['total_sum'];
    }

If you want the WHOLE GLOBAL sum, you have to way:

  • Modify your query in that way:

    SELECT SUM(retailer.basket_value) as total_sum                 
    FROM retailer
    
  • Sum into while loop like: $total += $row['total_sum'];