Jump to content

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.

 

Gord

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.