PHP: Voting System (From 1 to 5)
Back to: PHP: Main
You should know:
You should already know HTML/XHTML and have the most basic of an understanding of PHP and how it works. If you need to learn any of these, just head over to http://www.w3schools.com
Very recomended you know mysql or phpMyAdmin and fairly well
The voting panel
First we need to make clickable numbers that allows the users to click and vote. You can make the numbers using image links but for simplicity sake, we'll use text links in this. So here is how you'll create the numbers in html. Replace all [ with < and ] with >
[a href="website.com/processvote.php?vote=1"]
1[/a]
[a href="website.com/processvote.php?vote=2"]
2[/a]
[a href="website.com/processvote.php?vote=3"]
3[/a]
[a href="website.com/processvote.php?vote=4"]
4[/a]
[a href="website.com/processvote.php?vote=5"]
5[/a]
Okay so now we've got that created. I'll explain the reason for why this is the way it is when we create the processvote.php.
MySQL Table
I'm going to assume you use phpMyAdmin or know how to create mySQL tables in mySQL. All we really need is a column for is the current score (call it current_score) and an autoincriment (called id) incase you want to create a voting panel for more than one piece of content on your site. Have it's default set to 0. Everything starts at 0 and when people vote, it'll work it's way up.
The processvote.php file
So now let's create the processvote.php file.
<?php
// connect to your database
include('dbconnect.php');
// for starters lets use $_GET to get the number in the URL that person voted. For example, we are getting the number represented by x:
[a href="website.com/processvote.php?vote=x]1
[/a]
Replace x with the same number that the person was to click in the html code. So here goes nothing
$vote = $_GET['vote'];
// we just got the value that's in the URL that's called vote like I have already stated
// now let's check to see if it's a number
if(!is_numeric($vote)){
echo 'Vote must be a number';
die();
}
// okay, now let's make sure that it's equal to or between 1 and 5
if($vote < 1 || $vote > 5){
echo 'You can only vote between 1 and 5!';
die();
}
// now let's get the current score from the datbase and average it with new vote. Let's assume that the id in the database for this particular voting panel is 1.
$currentscore = mysql_fetch_array(mysql_query("SELECT * FROM table WHERE id='1'"));
$currentscore = $currentscore['current_score'];
$newscore = ($currentscore + $vote) / 2;
// now let's submit it into the database.
$submitscore = mysql_query("UPDATE table SET current_score=$newscore WHERE id='1'");
?>
Displaying the score
Now the easy part. Displaying the score.
<?php
$score = mysql_query("SELECT score FROM table WHERE id='1'");
echo 'Score: '.number_format($score, 2).'%';
?>
And badabing... there you have it. Hope you've learned something. This is a little sloppy but i was just giving it a shot!