Average numbers in PHP & MySQL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mikes1471
Forum Commoner
Posts: 88
Joined: Sat Jan 24, 2009 3:29 pm

Average numbers in PHP & MySQL

Post 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
Sephern
Forum Commoner
Posts: 73
Joined: Sun Jan 04, 2009 4:44 pm

Re: Average numbers in PHP & MySQL

Post 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'");
 
mikes1471
Forum Commoner
Posts: 88
Joined: Sat Jan 24, 2009 3:29 pm

Re: Average numbers in PHP & MySQL

Post by mikes1471 »

That's cool thankyou
Post Reply