Ahsan Imtiaz Ahsan Imtiaz - 1 year ago 74
MySQL Question

Adding values in associative array

I'm new to php. This is my code

$retval = $conn->query("Select points from evaluation_log where session_id='{$sessionid}';");
while($record = $retval->fetch_array(MYSQLI_ASSOC))
$result[]= $record;

The purpose of this query is to return multiple points against an id from the database which i'm storing in an array. Now I want to take sum of these points in the array. How should I do that.

Answer Source

If you absolutely must use your example then this would work:

$retval = $conn->query("select points from evaluation_log where session_id='{$sessionid}'");

$sum = 0;

while($record = $retval->fetch_array(MYSQLI_ASSOC)) 
    $sum+= $record['points'];

echo $sum;

However, this should be simpler:

$retval = $conn->query("select sum(points) as sum_points from evaluation_log where session_id='{$sessionid}'");

$record = $retval->fetch_array(MYSQLI_ASSOC);

echo $record['sum_points'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download