-1

I'm trying to get the sum of a column from my database. When I try this code I get the error Undefined index: sum(col_1). How can I do this? I'm a real beginner so keep it a bit simple.

$sql = "SELECT * FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
    $col_ans[1] = $rows['sum(col_1)'];
        echo $col_ans[1];
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Hydra
  • 5
  • 3
  • 1
    Tip: You can use `print_r($rows)` to see what the array indexes are. – Bill Karwin Jan 13 '19 at 08:30
  • Possible duplicate of [PHP: “Notice: Undefined variable”, “Notice: Undefined index”, and “Notice: Undefined offset”](https://stackoverflow.com/q/4261133/). – Funk Forty Niner Jan 13 '19 at 14:46
  • Tip: You may need to make sure to fields exist in the array before you are accessing them. Ex. Can use ternary operator as below. $x = isset($rows['col_1_sum']) ? $rows['col_1_sum'] : 'no-value' Learn more about ternary operator https://www.codementor.io/@sayantinideb/ternary-operator-in-php-how-to-use-the-php-ternary-operator-x0ubd3po6 – NiroshanJ May 13 '21 at 06:41

2 Answers2

3

You can easily find sum of a column this way.

$sql = "SELECT sum(col_1) as col_1_sum FROM table_1";
$run = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_assoc($run)){
echo $rows['col_1_sum'];
}
Yasii
  • 1,702
  • 1
  • 10
  • 15
1

Your problem is that you didn't use the SUM() function inside your query, so you won't get any sum from the query

You can also try the following:

$query =  "SELECT productName, SUM(productQty) AS 'Products Ordered'
FROM ctrlaproducttab
GROUP BY productName
";
$result = mysqli_query($con,$query);

while($row = mysqli_fetch_assoc($result))
{ 
    $productName = $row['productName'];
    $itemsOrdered = $row['Products Ordered'];
}

Notice that we're giving an alias name Products Ordered to the result of expression SUM(productQty), and now we can use this alias name as an index in the associative array returned by mysqli_fetch_assoc()

krishna
  • 26
  • 1