Page 1 of 1

Average numbers in PHP & MySQL

Posted: Sun Jul 05, 2009 11:05 am
by mikes1471
Hi everyone,

I know how to work out an average number but was wondering if anyone could suggest a way in which this can be done in a rating sense.
I don't think it's necessary to store each vote in a table, presumably it would be best to grab the current value, add the new vote and divide by total number of votes (+1) then enter the result as the new value?
So two stored values are needed, total votes and current average?

Just asking if there is anything more to consider really and if anyone can represent this sum in php

Re: Average numbers in PHP & MySQL

Posted: Sun Jul 05, 2009 12:47 pm
by Sephern
That would be the way that I'd do it.

Assuming you have several polls, and you have a database with the fields Poll_ID, Current_Average and Total_Votes.
The user has voted in the poll, setting a GET with the poll ID, and a POST of the number that they have voted.

Code: Select all

 
$dbhost = ''; //Enter relevant database info
$dbname = '';
$dbuser = '';
$dbpass = '';
$dbconnect = mysql_connect($dbhost,$dbuser,$dbpass)
    or die("Unable to connect to the database");
 
$selectdb = mysql_select_db($dbname);
 
 
$pollID = $_GET['poll'];
$uservote = $_POST['vote'];
$pollquery = mysql_query ("SELECT current_num FROM your_table WHERE Poll_ID = '$pollID'");
$pollarray = mysql_fetch_array ($query);
$currentval = $pollarray['Current_Value'];
$votes = $pollarray['Total_Votes'];
 
$currentval = $currentval + $uservote;
$votes = $votes + 1;
 
$currentval = $currentval / $votes;
 
$updatepoll = mysql_query("UPDATE your_table SET Current_Value = '$currentval' WHERE Poll_ID = '$pollID'");
$updatevotes = mysql_query ("UPDATE your_table SET Total_Votes = '$votes' WHERE Poll_ID = '$pollID'");
 

Re: Average numbers in PHP & MySQL

Posted: Sun Jul 05, 2009 1:09 pm
by mikes1471
That's cool thankyou