Jump to content


Photo

Adding a variable with the same name


  • Please log in to reply
3 replies to this topic

#1 monkeybidz

monkeybidz
  • Members
  • PipPipPip
  • Advanced Member
  • 330 posts

Posted 17 May 2006 - 01:43 AM

I am trying to add variables with the same name, but different row. The number of rows and amount will vary depending on the item i will be looking at.

This is what i have now, which is not correctly adding the $listing_fee

$listing_fee = number_format($listing_fee,2);


$total_due = $listing_fee * mysql_num_rows($result);
$total_due = number_format($total_due, 2);

What im trying to do is add $listing_fee + itself depending on the number of rows result. If i have 1 row, $total due is fine. When a new row with the same variable is auto created it adds incorrectly.

Can someone help? [img src=\"style_emoticons/[#EMO_DIR#]/wink.gif\" style=\"vertical-align:middle\" emoid=\":wink:\" border=\"0\" alt=\"wink.gif\" /]

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 17 May 2006 - 02:03 AM

You should only use the number_format() function when you want to display a number, not when you're going to be using it in computations.

Ken

#3 monkeybidz

monkeybidz
  • Members
  • PipPipPip
  • Advanced Member
  • 330 posts

Posted 17 May 2006 - 05:27 AM

$total_due is the final display result of the computation.

If mysql_num_rows result in more than one row, say 5. Each result row contains $listing_fee, but with different values. I want to add $listing_fee to itself for each row and get a $total_due.


#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 17 May 2006 - 02:47 PM

Try something like this:
<?php
$q = "select listing_fee from yourtable";
$rs = mysql_query($q);
$total = 0;
while ($rw = mysql_fetch_assoc($rs))
     $total += $rw['listing_fee'];
echo 'Total Fee: ' . number_format($total,2)."<br>\n";
?>

The "+=" operator means "take the value on the right and add it to the value on the left" it is equivalent to:
<?php $total = $total + $rw['listing_fee']; ?>

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users