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.
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'];
Below code will be more optimum use group_concat and array_sum
$retval = $conn->query("Select group_concat(points separator ',') as points from evaluation_log where session_id='{$sessionid}';");
$result=array();
while($record = $retval->fetch_array(MYSQLI_ASSOC)) // while loop only once by using group_concat
{
$result[]= explode(',',$record);
}
$sum_of_points = array_sum($result);
echo $sum_of_points;
You can directly use SUM function in you MySQL query that you will get in array.