Forum Moderators: coopster

Message Too Old, No Replies

Simplify poll script to query 50 polls

50 polls don't want to repeat the same query 50 times

         

s9901470

1:42 pm on May 28, 2005 (gmt 0)

10+ Year Member



Hi there

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>

mcibor

9:24 pm on May 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is fairly easy to achieve:

$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>";
}

Hope this helps!
Michal Cibor

s9901470

12:02 pm on May 29, 2005 (gmt 0)

10+ Year Member



That works great, many thanks!

What if I want to have the topics labelled? At the moment it lists 'topic 50' but in another table I have the name of the poll e.g. 'pizza' and want that to be listed instead of the number 50.

Any suggestions?

mcibor

6:40 pm on May 29, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$name;//array with names

$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