List:General Discussion« Previous MessageNext Message »
From:Nuno Pereira Date:September 13 2005 3:17pm
Subject:Re: Newbie MySQL/PHP question re output formatting
View as plain text  
Bill Whitacre wrote:
> I can get this to work just fine:
> 
> 
>> <?php
>>     $number = 23999.39;
>>     print "$";
>>     print number_format($number, 2);
>>
>> ?>
>>
> 
> Comes out $23,999.39
> 
> I'd like use the number_format() thingie on an array returned from a  
> mysql_query.
> 
> My current program snippet looks like:
> 
> 
>>     $res = mysql_query("SELECT org, COUNT(*), SUM(annual_cost) AS  
>> cost FROM a05
>>     GROUP BY org ORDER BY cost DESC",$dbh);
>>
>>     if (!$res) {
>>       echo mysql_errno().": ". mysql_error ()."";
>>       return 0;
>>     }
>>
>>     print "<table border=1>";
>>
>>     while ($thearray = mysql_fetch_array($res)) {
>>
>>         printf("<tr><td> {$thearray[org]} </td>
>>         <td align=right> {$thearray["COUNT(*)"]} </td>
>>         <td align=right> $ {$thearray[cost]} </td></tr>");
>>
>>     }
>>
>>     print "</table>";
>>
> 
> and works fine -- see <http://ibbmonitor.com/sked_1.php>, 3rd block  of 
> stuff down.
> 
> If I replace
> 
> {$thearray[cost]}
> 
> with
> 
> number_format({$thearray[cost]}, 2)
> 
> I get
> 
> $ number_format(7842554.24, 2)

The issue is that PHP replaces $thearray[cost], with the contents of 
that variable (that is an array, it doesn't matter). But in the second 
case it replaces the same thing ($thearray[cost]), with the contents of 
the variable, but you want to place there the result of the function.
To do date change the first line from

printf("<tr><td> number_format({$thearray[cost]}, 2) </td>

to

printf("<tr><td> ".number_format({$thearray[cost]}, 2)." </td>

> in the cell where I would expect to get
> 
> $ 7,842,554.24
> 
> Any idea what I'm doing wrong?
> 
> Clearly, I don't understand arrays very well.
> 
> Thanks VERY much for any help on this.
> 
> bw
> 
> ---
> Bill Whitacre
> bw@stripped
> 
> 

-- 
Nuno Pereira
Thread
Newbie MySQL/PHP question re output formattingBill Whitacre13 Sep
  • Re: Newbie MySQL/PHP question re output formattingJigal van Hemert13 Sep
  • Re: Newbie MySQL/PHP question re output formattingNuno Pereira13 Sep
    • Re: Newbie MySQL/PHP question re output formattingJasper Bryant-Greene13 Sep