Forum Moderators: coopster
I have a polling system where votes are stored in a mysql table. I then get the total number of ratings and the average rating as shown below. However, there are 50 polls and I don't want to repeat the same query 50 times. Can anyone suggest a way to simplify this code?
Thank you in advance.
<?
$query = "SELECT SUM(votes) FROM poll_data WHERE poll_id=1"; $id1 = mysql_query($query) or die("Select Failed!"); $total1 = mysql_fetch_array($id1); $query = "SELECT AVG(votes) FROM poll_data WHERE poll_id=1"; $id1 = mysql_query($query) or die("Select Failed!"); $avg1 = mysql_fetch_array($id1);
// and so on up to 50
$query = "SELECT SUM(votes) FROM poll_data WHERE poll_id=50"; $id50 = mysql_query($query) or die("Select Failed!"); $total50 = mysql_fetch_array($id50); $query = "SELECT AVG(votes) FROM poll_data WHERE poll_id=50"; $id50 = mysql_query($query) or die("Select Failed!"); $avg50 = mysql_fetch_array($id50);
?>
<p><strong>Topic 1</strong><br>Total number of ratings:<? echo $total1[0];?><br>Average rating:<? echo $avg1[0];?> (range 1 to 5)</p>
<p><strong>Topic 50</strong><br>Total number of ratings:<? echo $total50[0];?><br>Average rating:<? echo $avg50[0];?> (range 1 to 5)</p>
$query = "SELECT SUM(votes) as total, AVG(votes) as mean FROM poll_data GROUP BY poll_id";
This should give you a 50 row array of results for every poll.
Then just fetch the result:
$i = 0;
$ask = mysql_query($query) or die("Select Failed!");
while($row = mysql_fetch_array($ask))
{
++$i;
echo "<p><strong>Topic $i</strong><br>Total number of ratings: ".$row['total']."<br>Average rating: ".$row['mean']." (range 1 to 5)</p>";
}
$i = 0;
$ask = mysql_query($query) or die("Select Failed!");
while($row = mysql_fetch_array($ask))
{
echo "<p><strong>Topic " . $name[$i++] . "</strong><br>Total number of ratings: ".$row['total']."<br>Average rating: ".$row['mean']." (range 1 to 5)</p>";
}
This will do it. Store the array in such format: $name = array("pizza", "hamburger", "etc");
Best regards
Michal Cibor