Poll and Voting System with PHP and MySQL

Posted on

Poll or voting system is used in many websites, specially in news sites for survey purpose. So if you’re developing a website and wants to implement voting system then you’re here at right place. You can easily develop voting system using PHP and MySQL. So in this tutorial you will learn how to create voting system with PHP and MySQL. We will create a live example of voting system with results page to view poll results.

As we will cover this tutorial with live example to create Poll with vote functionality with PHP and MySQL, so the file structure for this example is following.

  • index.php
  • results.php
  • Poll.php

Step1: Create MySQL Table and Insert Records
We will handle poll and its with single database table. So first we will create MySQL database table poll using below query.
CREATE TABLE `poll` (
`pollid` double NOT NULL,
`question` text,
`poll_date` double DEFAULT NULL,
`options` varchar(250) DEFAULT NULL,
`votes` varchar(250) DEFAULT NULL,
`close` tinyint(1) DEFAULT NULL,
`number_options` tinyint(3) DEFAULT NULL,
`poll_timeout` double DEFAULT NULL,
`voters` int(11) DEFAULT NULL,
`public` tinyint(1) DEFAULT NULL,
`last_vote_date` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

For displaying poll with options, we will insert below data into poll table using below query.
INSERT INTO `poll` (`pollid`, `question`, `poll_date`, `options`, `votes`, `close`, `number_options`, `poll_timeout`, `voters`, `public`, `last_vote_date`) VALUES
(1, 'Which team has the most wins in all of IPL?', 1524829888, 'Sunrisers||||Kings||||Daredavils||||Nightriders', '0||||0||||0||||0', 0, 4, 0, 0, 0, 1524836731);

Step2: Create Poll Class with Methods
First we will create Poll.php file and define class Poll to handle functionality like to connect to MySQL database, get poll, get vote and update vote.
<?php
class Poll{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $database = 'phpzag_demos';
private $pollTable = 'poll';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$conn = new mysqli($this->host, $this->user, $this->password, $this->database);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
}else{
$this->dbConnect = $conn;
}
}
}
private function getData($sqlQuery) {
$result = mysqli_query($this->dbConnect, $sqlQuery);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getPoll(){
$sqlQuery = 'SELECT pollid, question, options, votes, voters FROM '.$this->pollTable;
return $this->getData($sqlQuery);
}
public function getVotes($pollid){
$sqlQuery = 'SELECT votes, voters FROM '.$this->pollTable.' where pollid = '.$pollid;
$result = mysqli_query($this->dbConnect, $sqlQuery);
return mysqli_fetch_array($result, MYSQL_ASSOC);
}
}
?>

Step3: Display Poll with Options
In index.php file, we will include class file Poll.php and then object of Poll and get poll details to display. As have stored poll options in database as string separated with ||||, so we will convert options string into an options array and display poll options.
<?php
include ('Poll.php');
$poll = new Poll();
$pollData = $poll->getPoll();
?>
<form action="" method="post" name="pollForm">
<?php
foreach($pollData as $poll){
echo "<h3>".$poll['question']."</h3>";
$pollOptions = explode("||||", $poll['options']);
echo "<ul>";
for( $i = 0; $i < count($pollOptions); $i++ ) {
echo '<li><input type="radio" name="options" value="'.$i.'" > '.$pollOptions[$i].'</li>';
}
echo "</ul>";
echo '<input type="hidden" name="pollid" value="'.$poll['pollid'].'">';
echo '<br><input type="submit" name="vote" class="btn btn-primary" value="Vote">';
echo '<a href="results.php?pollID="'.$poll['pollid']."> View Results</a>";
}
?>
</form>

Step4: Implement Poll Voting Functionality
Now we will handle poll vote functionality when poll vote form submitted. We will get poll vote form details and store into an array and passed to Poll method $poll->updateVote($pollVoteData) to handle poll vote functionality. We will also use PHP COOKIE to not allow the user to vote for multiple times.
include ('Poll.php');
$poll = new Poll();
if(isset($_POST['vote'])){
$pollVoteData = array(
'pollid' => $_POST['pollid'],
'pollOptions' => $_POST['options']
);
$isVoted = $poll->updateVote($pollVoteData);
if($isVoted){
setcookie($_POST['pollid'], 1, time()+60*60*24*365);
$voteMessage = 'Your have voted successfully.';
} else {
$voteMessage = 'Your had already voted.';
}
}

We will create method updateVote() in Poll.php to handle poll vote functionality. As we have stored poll votes in database table as separated with |||| as string for each options. So we will convert votes string into an array and handle poll vote increment functionality to add vote for related option and also increment vote counter. Then updated poll table with votes and voters count.
public function updateVote($pollVoteData) {
if(!isset($pollVoteData['pollid']) || isset($_COOKIE[$pollVoteData['pollid']])) {
return false;
}
$pollVoteDetails = $this->getVotes($pollVoteData['pollid']);
$votes = explode("||||", $pollVoteDetails['votes']);
$votes[$pollVoteData['pollOptions']] += 1;
implode("||||",$votes);
$pollVoteDetails['voters'] += 1;
$sqlQuery = "UPDATE ".$this->pollTable." set votes = '".implode("||||",$votes)."' , voters = '".$pollVoteDetails['voters']."' where pollid = '".$pollVoteData['pollid']."'";
mysqli_query($this->dbConnect, $sqlQuery);
return true;
}

Step5: Display Poll Results
In results.php file, we will display poll vote results by calling Poll method $poll->getPoll() to get poll vote details for each options. Then we will handle functionality to get percent of vote for each option and display with Bootstrap progress bar HTML.
include ('Poll.php');
$poll = new Poll();
$pollData = $poll->getPoll();
foreach($pollData as $poll) {
echo "<h3>".$poll['question']."</h3>";
$pollOptions = explode("||||", $poll['options']);
$votes = explode("||||", $poll['votes']);
for( $i = 0; $i<count($pollOptions); $i++ ) {
$votePercent = '0%';
if($votes[$i] && $poll['voters']) {
$votePercent = round(($votes[$i]/$poll['voters'])*100);
$votePercent = !empty($votePercent)?$votePercent.'%':'0%';
}
echo '<h5>'.$pollOptions[$i].'</h5>';
echo '<div class="progress">';
echo '<div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:'.$votePercent.'">'.$votePercent.'</div></div>';
}
}

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo [sociallocker]Download[/sociallocker]

Leave a Reply

Your email address will not be published. Required fields are marked *