I want to fetch the amount from database and want to store total of those amount in a variable and print that variable. I searched and got a link to add a number to itself and tried it in my code but i didn't get the output as was expected.
Here is my code..
<?php
$cid = $_REQUEST['cname'];
$cmd = mysql_query("SELECT amount FROM fund WHERE clientid = $cid");
while($row = mysql_fetch_array($cmd)) {
$acnt += $row['amount'];
echo $acnt;
}
?>
The output that I have got through this is like- 10001200130015002000
.
But I am just expecting the last added value that is 2000
only as my output.
You are echoing the value each time inside the while loop that's why you are getting the amount displayed each time. Echo the amount after the while loop.
while($row = mysql_fetch_array($cmd))
{
$acnt += $row['amount'];
}
echo $acnt;
Try This Code:
You don't have need to use of loop.on behalf that just do sum of amount using sql query.
$cmd = mysql_query("select sum(amount) amount from fund where clientid = $cid");
$row = mysql_fetch_array($cmd);
$acnt = $row['amount'];
echo $acnt;
Let MySQL do the work for you instead of doing the loop:
$cmd = mysql_query("select sum(amount) amount from fund where clientid = '$cid'");
$row = mysql_fetch_assoc($cmd);
$acnt = $row['amount'];
echo $acnt;
Btw, you must escape raw input or use a formatting function like this:
$sql = sprintf('select sum(amount) amount from fund where clientid = %d', $cid);
$cmd = mysql_query($sql);
// ...
Or better yet, use either PDO or mysqli and learn about prepared statements.