Jump to content


This topic is now archived and is closed to further replies.


Accessing an array component that has been calculated

Recommended Posts

Hello, first post. I\'m a bit of a cook-book coder, but I clean up well and generally smell nice. I\'m creating a small personal app for practice with PHP and MySQL and need to tug on some expert coatails.


I have a returned MySQL array which is displaying just dandy on a PHP page with a SELECT - one of the elements of that array is a calculated variable $total, which is the quotient of two db fields pulled with the SELECT ($total = $units * $value;). There is a $total in every row in the array produced in a WHILE loop.


Two questions:

1) Can someone tell me how I can access the $total values so that I can further add them up outside of the WHILE function? I can see them on the page, but am unclear how to target them and add them up outside of the above loop. A code example would be very helpful.


2) I can\'t seem to figure out how to format the above $total variable. Because it is created by muliplying two decimal format numbers, it returns numbers with multiple decimals - I only want .02, because it is a money figure. settype($total, \'integer\'); returns only integers, no decimals (duh)...settype($total, \'decimal (7,2)\'); doesn\'t work - but I do get three and four decimals...


Thanks for any help - hope I\'m not boring anyone with my brainlessness.



Share this post

Link to post
Share on other sites

I am not quite clear with your 1st question



select (absentdays + presntdays) as total from students


Now in the above query absentdays and presentdays are two fields in my table and I add them using the query.


So my code will be like this


while ($row = mysql_fetch_array($sql))


echo $row[\'total\'];



The trick is I am using total as an alias name to the two colums that are added.


I hope I am clear.


2. You can use the round fucntion in PHP to do this


$a = round(1.967,2)


Will return 1.97

Share this post

Link to post
Share on other sites

1. SELECT SUM(units * value) as grandtotal FROM tablename


2 echo number_format($total, 2);



Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.