php - For each / query doesn't give the right value -
i have table in database. want ltotal
value leave
table, , count of ltotal
. here query , code use:
$annual_query = pg_query("select ltotal leave lapplicant='adam' , ltype=2"); $annual_result = pg_fetch_array($annual_query); if (pg_num_rows($annual_query) > 0) { foreach ($annual_result $data) { $total_annual = $total_annual + $data; } print($total_annual); }
there 3 records in table leave lapplicant='adam'
, ltype=2
.
each ltotal
1.
when tried runprint($total_annual)
result 2 (it must 3).
then tried print_r($annual_result['ltotal']
), results 1 (it must 1,1,1).
can me? thank you.
pg_fetch_array()
returns 1 row numeric , associative keys (same value twice when traversed). should use pg_fetch_all()
, traverse or use while loop on consecutive rows.
$total_annual = 0; $annual_query = pg_query("select ltotal leave lapplicant='adam' , ltype=2"); while ($row = pg_fetch_array($annual_query)) { $total_annual = $total_annual + $row['ltotal']; } print($total_annual);
or
$total_annual = 0; $annual_query = pg_query("select ltotal leave lapplicant='adam' , ltype=2"); $annual_result = pg_fetch_all($annual_query); foreach ($annual_result $row) { $total_annual = $total_annual + $row['ltotal']; } print($total_annual);
Comments
Post a Comment