Need help with summing prices from db

Hello, i wrote a query which should sum all prices of the categories and group them by category.

$query = "SELECT SUM(price) FROM costs GROUP BY category";

The idea is to later then put every sum of each category in a variable that i can show on that category’s page.
Can someone help me with this code cuz it’s the first time for me doing this.

Why would you want to calculate for all categories if it’s going to be shown on a single category’s page?

And what is your problem in particular? Did you get any data from a database before? If so, why don’t you do just the same?

if($stmt = $conn->prepare("SELECT price FROM costs WHERE userid=? AND category=?")) {
            $stmt->bind_param("is", $session_id, $category);
            $stmt->execute();
            $prices_object = $stmt->get_result();
        }

How do i count all the prices together and echo the total?

sum() price and group by userid + category

at least every aggrgated column (e.g. sum()'ed) needs to be aggregated itself (even when mysql allows otherwise)

He is going to show it on the category page. Means he needs the data for a single category only and thus no aggregation.

From years of answering questions I learned that you have to always read between the lines. Or, rather, all the lines diligently. The described business case often contradicts with a question that was asked

thx for the replies guys, I searched and experimented a bit and came up with this:

$get_total = "SELECT SUM(price) as total FROM costs WHERE userid='$session_id' AND category='$category'";
    if ($results = mysqli_query($conn, $get_total)) {
        $show_s = mysqli_fetch_assoc($results);
        $total = $show_s['total'];
    } 

This works perfect atm so i’m using this for my categories.

from my last years experiences on this i learned to encourage people to be more precise :slight_smile: (but i guess my sucess rate is lower)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.