Ahsan Imtiaz Ahsan Imtiaz - 4 months ago 9
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}';");
$result=array();
$temp=array();
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

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'];