Page 1 of 1

How to make an array of the result of a while loop

Posted: Wed Dec 02, 2009 4:45 pm
by tuxiow
Hello All,

How can I make an array of the result of my while loop.

I have this......

Code: Select all

$query        =    "SELECT rating FROM ratings WHERE imageID = '$imageID'"; 
$result        =    mysql_query($query); 
$rating        =    mysql_fetch_array($result); 
 
while($rating        =    mysql_fetch_array($result)){ 
$ratings        =    $rating['rating'];
So I am retrieving the value of 'rating' from my table on each loop and I want to create an array of the results.

How could I achieve this?

Regards Paul

Re: How to make an array of the result of a while loop

Posted: Wed Dec 02, 2009 4:59 pm
by Weiry
if you only want to retrieve an array of data from a query and put it in an array, you dont need the while loop.

Code: Select all

$query = "SELECT `rating` FROM `ratings` WHERE `imageID` = '{$imageID}'";
$result = mysql_query($query);
$ratings = mysql_fetch_assoc($result); // this is the retrieved array
 

Re: How to make an array of the result of a while loop

Posted: Wed Dec 02, 2009 5:07 pm
by AbraCadaver
You almost had it. There are several ways. Here's one:

Code: Select all

$query = "SELECT rating FROM ratings WHERE imageID = '$imageID'";
$result = mysql_query($query);
 
while($row = mysql_fetch_array($result)){
    $ratings[] = $row['rating'];
}
-Shawn

Re: How to make an array of the result of a while loop

Posted: Thu Dec 03, 2009 3:47 pm
by tuxiow
Thanks for that Shawn,

That almost works perfectly. The only thing is, it is missing the first result in the while loop.

eg. I have 9 records in the table with values of 2, 4, 1, 2, 5, 3, 5, 4, 3. Totaling 29.

My array output is this.....

Array ( [0] => 4 [1] => 1 [2] => 2 [3] => 5 [4] => 3 [5] => 5 [6] => 4 [7] => 3 )

As you can see it is missing off the first record value of 2.

Here is my code......

Code: Select all

$result     =   mysql_query("SELECT COUNT(*) FROM ratings WHERE imageID = '$imageID'");
$row        =   mysql_fetch_row($result);
$numrows    =   $row[0];
 
$query      =   "SELECT * FROM ratings WHERE imageID = '$imageID' ORDER BY ratingID DESC";
$result     =   mysql_query($query);
$rating     =   mysql_fetch_array($result);
 
while($rating = mysql_fetch_array($result)){
$ratings[] = $rating['rating'];
}
$sum_total  =   array_sum($ratings);
 
$new_rating =   $sum_total/$numrows;
 
echo $new_rating;
echo $numrows;
echo $sum_total;
 
print_r($ratings);
Why would it be doing this. Thanks.

Paul

Re: How to make an array of the result of a while loop

Posted: Thu Dec 03, 2009 4:03 pm
by AbraCadaver
Delete line 7 in your code.

Actually, even better, I think you can delete lines 1-3 and replace line 7 with this:

Code: Select all

$numrows = mysql_num_rows($result);
-Shawn