Jump to content


Photo

Accessing an array component that has been calculated


  • Please log in to reply
2 replies to this topic

#1 gomac

gomac
  • New Members
  • Pip
  • Newbie
  • 1 posts
  • LocationToronto

Posted 23 December 2003 - 07:04 PM

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.

Gord

#2 shivabharat

shivabharat
  • Members
  • PipPipPip
  • Advanced Member
  • 371 posts
  • LocationChennai, India

Posted 23 December 2003 - 08:00 PM

I am not quite clear with your 1st question

1.
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
Knowledge --- Reading Enriches Mind But Sharing Enhances It.[br][br]Note: Before you request help enusre that you have had a look at the tutorials @phpfreaks

#3 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,016 posts

Posted 23 December 2003 - 08:01 PM

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

2 echo number_format($total, 2);

hth
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users