Add values from MySQL result together from array

I'm not sure if I'm overthinking this and being stupid but I'm trying to add all the values from my MySQL result.

Here is my code to fetch the values and store them in an array:

$query = "SELECT value FROM table";
$result = mysqli_query($dbcon, $query);
$array = array();

if(mysqli_num_rows($result) > 0 ){
   while($row = mysqli_fetch_assoc($result)) {
       $array[] = $row;
   }
}
      
print_r($array);

Now I just need to figure out how I can add these values together and use this array for other things like working out the average. If there is an easier way to do this than storing the results in an array then please let me know.

Any help is much appreciated.

1 answer

  • answered 2021-04-21 15:48 Harrison

    Managed to figure this out myself, I used the below code:

    $query = "SELECT SUM(column) AS value_sum FROM table";
    $result = mysqli_query($dbcon, $query);
    $row = mysqli_fetch_assoc($result);
    $sum = $row['value_sum'];
    

    I guess I was overthinking it.