How to create a POLL system using PHP, MySQL and Ajax

Thursday, October 7, 2010

In this tutorial I will show you how to create a basic POLL system using PHP, MySQL and Ajax. This poll will have some great features like: nobody can vote multiple times and the result of the poll is shown automatically after voting without refreshing the page.
Here is a live demo:
The poll system uses a MySQL table to store the votes. This table requires only two columns:
vote - the number of the selected option (the "Yes..." option has the number 2)
ip - the ip is used to prevent multiple votes
To create the table you can use the following file:
create-table.php
mysql_connect('host', 'database', 'password')
or die (mysql_error());
mysql_select_db('database')
or die (mysql_error());
mysql_query("create table poll(
vote tinyint(2) NOT NULL,
ip varchar(15) NOT NULL,
PRIMARY KEY (ip)
)") or die (mysql_error());
echo "Complete.";
?>
The poll itself is made from two files. One contains the forms and the javascript and ajax parts, and an another file what`s called by the first one.
The first file (poll.php) just sends the selected option number to the second file (vote.php) and displays the response. Here is my poll.php:

poll.php
<html>

<head>
<style>
.votes {
overflow:hidden;
background:#CCC;
height:20px;
width:100px;
margin:5px 0 0 23px;
float:left;
}
.percentage {
overflow:hidden;
background:#F00;
height:20px;
}
.option {
position:absolute;
width:100px;
height:20px;
}
.percentagetext {
overflow:hidden;
width:75px;
height:20px;
margin:5px 0 0 0;
float:left;
text-align:left;
}
</style>
</head>

<body>
<div id="poll" style="width:200px;overflow:hidden;text-align:center;">
Do you like this poll?<br/>
<div style="text-align:left;width:180px;margin:0 auto;">
<input type="radio" name="poll" id="poll1" checked>Yes, it`s great<br/>
<input type="radio" name="poll" id="poll2">Yes...<br/>
<input type="radio" name="poll" id="poll3">Not bad...<br/>
<input type="radio" name="poll" id="poll4">No!<br/>
</div>
<input type="button" value="Vote!" onClick="vote();"/>
</div>
<script type="text/javascript">
function vote(){
for(var i=1;i<=4;i++){
if(document.getElementById('poll' + i).checked){
//Check which one has been checked
var sendto = 'vote.php?vote=' + i;
}
}
// Call the vote.php file
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest;
xmlhttp.open("GET",sendto,false);
xmlhttp.send(null);
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET",sendto,false);
xmlhttp.send();
}
//Output the response
document.getElementById('poll').innerHTML = xmlhttp.responseText;
}
</script>

</body>
</html>
The CSS code is used to bring style to the response.

Now let`s create the vote.php file. This file will need to check if the user has already voted or not (by checking the ip) and it will need to calculate the percentage of votes and output the result in HTML format:

vote.php
<?php
//Connect to MySQL
mysql_connect('host','database','password');
//Select database
mysql_select_db('borcsa9_database');
//Check if the current user has already voted or not
//@$REMOTE_ADDR is used to get the ip of the user
if(mysql_num_rows(mysql_query("select * from poll where ip = '" . @$REMOTE_ADDR . "'")) != 0){
echo 'You can vote only once!';
}
else{
//If the user had not voted then insert the new vote in the poll table
mysql_query("insert into poll values ('" . $vote . "', '" . @$REMOTE_ADDR . "')") or die (mysql_error());
}
$mostvotes = 0;
for($i=1;$i<=4;$i++){
//Create an array of votes for each option
$votes[$i] = mysql_num_rows(mysql_query("select * from poll where vote = " . $i));
if($votes[$i] > $mostvotes){
//Select the option with the higher number of votes
$mostvotes = $votes[$i];
}
//Each vote
$allvotes += $votes[$i];
}
$option[1] = 'Yes, it`s great';
$option[2] = 'Yes...';
$option[3] = 'Not bad...';
$option[4] = 'No!';
//Generate the result in a HTML form by calculating the percentage of each option and showing the number of votes
for($i=1;$i<=4;$i++){
echo "<div class='votes'><div class='option'>" . $option[$i] . "</div><div class='percentage' style='width:" . floor($votes[$i] / $allvotes * 100) . "px'></div></div><div class='percentagetext'> - " . floor($votes[$i] / $allvotes * 100) . "% (" . $votes[$i] . ")</div>";
}
?>
And the our poll system is ready to use. This is a very basic poll system, but this can be easily modified by adding more style or more functions to it.
If you have any question, don`t hesitate, ask!

18 comments:

In the web world who organizes time takes advantage! Congratulations for important web site................

Can you write the version used POST?
What happens if the program on the server does not return data? How can I handle this situaion?
Thank's alot!

Do you mean the version of PHP ?
I`m using PHP 5 but it should work on PHP 4 ,too

I get this error:
Unknown MySQL server host 'host' (11001) in C:\wamp\www\PollSystem\MyPoll\create_table.php on line 2
Unknown MySQL server host 'host' (11001)

What can i do to avoid this?

I get a error saying "Warning: Division by zero in C:\wamp\www\PollSystem\MyPoll\vote.php on line 33"

And line 33 is the line with the last echo command.

Can you please help me solve that problem?

Thanks!

Found out that it was because that the DB was empty. problem solve :)

I got..

Warning: Division by zero in /home/username/mydomain/vote/vote.php on line 32

Try to include a vote in the database:
Go to your mysql admin panel and add a vote (you can include anything for the ip)

Is there a non-JavaScript version of this script?

The same story, without javascript it will refresh the whole page, but I will create a version using only PHP ;)

I just want to say, you should not received all data from database. There are ways to get numbers you need just by using a proper SQL request. Imagine you have couple of thousands of votes and for every page refresh it transfer all data from db to server, just to find out how many rows are there ...

how do you add a vote in the mysql database? cuz i got that error too

nvm i figured it out, but it's still displaying this error:

You can vote only once!
Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32
Of Course!
- 0% (0)

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32
Sure
- 0% (0)

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32
Maybe
- 0% (0)

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32

Warning: Division by zero in /home/content/d/j/s/djsmiley/html/vote.php on line 32
Definitely not
- 0% (0)

Go here and try it and you'll see. The poll is in the left sidebar under the login menu.

nvm...
i thought since the "vote varchar value" had '2' in (), it meant u had to type a number of two digits. but i guess that just means the maxium number of options can only be two digits long, like from 1 to 99.
i put 12, but when i replaced it with 1 for option '1', it worked.
Thanks so much!

one last question, though. how do you apply the css above into a separate document and attach it to the poll results? i don't want to put it in the same document as the page the polls on.

Maybe you should create a .css file and use it on each of your pages.... (search for it e.g: external css)

If the poll doesn't work replace @$REMOTE_ADDR with $_SERVER['REMOTE_ADDR'] and $vote with $_GET['vote'] in the mysql_queries (in vote.php).

Thanks Anonymous,

It wasn't working for me so I changed $vote to $_GET['vote'].

Cheers from Ireland

Thanks for share,
This is the easiest way to create poll app with some bugs fix :) Otherwise, its pretty cool :D

Post a Comment