division by zero in MySQL result
| From: | Marc Antony Vose | Date: | Sun, 22 Oct 2000 15:29:01 +0000 |
| Subject: | division by zero in MySQL result | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-21638@lists.php.net to get a copy of this message | ||
Hi there.
I'm having a really obscure and strange problem. Sorry this is a little long, but I think the set-up is necessary.
I have a class which is making a selection out of MySQL and using the following construct to insert the data into an associative array called stuff:
if( @mysql_num_rows( $result ) ){
$counter = 0;
$keys = "";
while( $this_one = mysql_fetch_array( $result ) ){
// get the keys if we don't already have them
if( !$keys ){
$keys = array_keys( $this_one );
}
// step through the keys and add an associative array entry for each
for( $x=0; $x<count($keys); $x++ ){
$this->stuff[$counter]["$keys[$x]"] = $this_one[$keys[$x]];} $counter++; } } Sometimes, MySQL is performing a calculation before spitting stuff out. There are ten fields in the database which record the number of votes for a particular rating (1-10). I'll simplify the example to imagine people can rate something either 1, 2 or 3. So the select statement looks something like: SELECT products.*, (vote1+vote2+vote3) as num_votes, ((vote1+(vote2*2)+(vote3*3))/(vote1+vote2+vote3)) as rating FROM products NOW, everything was working perfectly. The class is spitting out data into stuff, so that after you instantiate the class you end up with something like: $this_product->stuff[0]["name"] = "Product Name" $this_product->stuff[0]["num_votes"] = 126 $this_product->stuff[0]["rating"] = 2.34 MY PROBLEM, however, seems to crop up whenever MySQL has to divide by zero in the output. Even if I am selecting 45 products, and only one of them has 0 votes, for some reason the key "rating" doesn't end up in the array "stuff". In other words, whenever there's a product in the output that hasn't been voted on, it nullifies the key name "rating" somehow. The bizarre thing is, the ratings DO come out in the numerical indexes of the array "stuff", just not the keyed entries. Unfortunately, I can't refer to the array information by number, because the number of columns returned is variable. I've been spinning my wheels on this for a few hours now and am hoping someone might have a suggestion as to why this is happening, or if there is any way around it. Is there a bug in my code above that makes the result name into the key? -- Marc Antony Vose http://www.suzerain.com/ When a man is generally detested, or when he is generally beloved, closer examination is necessary. -- K'ung-Tzu