[thelist] strange php/mysql display problem (solved)

Bob Meetin bobm at dottedi.biz
Tue Jun 8 09:25:42 CDT 2010


Jack Timmons wrote:
> On Mon, Jun 7, 2010 at 11:52 PM, Bob Meetin <bobm at dottedi.biz> wrote:
>   
>> This seems really simple, yet causes heartache.
>>
>> I am using a javascript program called flot to build charts and php/mysql to
>> feed data.  Almost everything works but when I run a very very simple mather
>> operation the chart fails.
>> $query = "select count(rating) as num_ratings, sum(rating) as sum_ratings
>> from some_table " ;
>> $result = mysql_query ($query);
>> $number_results = mysql_num_rows ($result);
>> if(mysql_num_rows($result)> 0)
>> {
>>  $row = mysql_fetch_array($result);
>>  $sum_ratings  = $row["sum_ratings"];  // the result here is "15"
>>  $num_ratings  = $row["num_ratings"]; // the result is "7"
>>
>>  # $avg_rating = $sum_ratings / $num_ratings;  // this causes failure in the
>> display
>>   $avg_rating = $sum_ratings / 7; // this works
>>
>>  $avg_rating = number_format($avg_rating,1,".",",");
>> }
>>     
>
> Is the data you're getting back from the query correct?
>
> You could also try  $num_ratings  = (int) $row["num_ratings"]
The data is good according to the eyeball mathematician.  I tried using 
(int) as noted above, thx, but that made no difference.  I was going to 
try system and bc as below in the PHP script but did not get it escaped 
properly (quotes):

<?php system "(avg_rating=$(echo 'scale=2; $num_ratings/$sum_ratings' | 
bc)"; ?>  // how do you escape this correctly?

The solution was to step further back and do the math in the mysql query 
as in:

sum(rating)/count(rating) as avg_rating,

-Bob



More information about the thelist mailing list