I have a table in my database. I want to get ltotal
value from leave
table, and then count all of ltotal
. Here are my query and code I use:
$annual_query = pg_query("select ltotal from leave where lapplicant='adam' and ltype=2");
$annual_result = pg_fetch_array($annual_query);
if (pg_num_rows($annual_query) > 0) {
foreach ($annual_result as $data) {
$total_annual = $total_annual + $data;
}
print($total_annual);
}
There are 3 records in the table leave where lapplicant='adam'
and ltype=2
.
Each ltotal
is 1.
When I tried to run print($total_annual)
the result is 2 (it must be 3).
Then I tried to print_r($annual_result['ltotal']
), the results is just 1 (it must be 1,1,1).
Can anyone help me? Thank you.
Tamil pointed out the immediate problem. However - why don't you just do this in SQL?
select sum(ltotal)
from leave
where lapplicant='adam' and ltype=2
pg_fetch_array()
returns just one row with numeric and associative keys (same value twice when traversed). You should use pg_fetch_all()
and traverse or use while loop on consecutive rows.
$total_annual = 0;
$annual_query = pg_query("select ltotal from leave where lapplicant='adam' and 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 from leave where lapplicant='adam' and ltype=2");
$annual_result = pg_fetch_all($annual_query);
foreach ($annual_result as $row) {
$total_annual = $total_annual + $row['ltotal'];
}
print($total_annual);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.