PHP MYSQL PDO SUM of columns -


i'm new php , i've searched past hour , read documentation find , nothing helping. have table has bunch of rows of data. i'm trying pick 1 column whole table , add them together. here got. tells me how many rows there match query, not total sum of column want. appreciated.

$res1 = $db->prepare('select sum(distance) trip_logs user_id = '. $user_id .' , status = "2"'); $res1->execute(); $sum_miles = 0; while($row1 = $res1->fetch(pdo::fetch_assoc)) { $sum_miles += $row1['distance']; } echo $sum_miles; 

you're returning 1 row in instance. modify summed column have alias:

select sum(distance) totdistance trip_logs .... 

now can can fetch row -

$row = $res1->fetch(pdo::fetch_assoc); echo $row['totdistance']; 

no need loop.


Comments