Simple Poll Example Using PHP, Bootstrap and MySQLi

This PHP tutorial helps to create a poll application using bootstrap. We will create a poll widget and submit data. MySQL database are used to store poll data. The User can see results as well using the result menu link.

There are many websites are using a Pool or Voting system to cater to user views. You can easily create polls using PHP and MySQL.

Create POLL database

First, We will create a MySQL 'test' database into MySQL server. Now create a poll table data using below SQL script.

CREATE TABLE `poll` (
  `id` int(11) 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;

Above table will store poll question, polls data and poll time.We will create a simple poll questions and store into 'poll' table.

INSERT INTO `poll` (`id`, `question`, `poll_date`, `options`, `votes`, `close`, `number_options`, `poll_timeout`, `voters`, `public`, `last_vote_date`) VALUES
(1, 'Which team will win the 2018 FIFA World Cup?', 1524829888, 'Brazil||||Argentina||||Spen||||France', '1||||2||||1||||1', 0, 4, 0, 5, 0, 1524836731);

We will use following files to create voting php example:

  • index.php: This file will use to define poll options to vote them.
  • poll.php: This file will have db connection and all poll methods.
  • results.php: This file will use to show poll results.

We will create index.php file and below code into this file:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style type="text/css">
  body { margin-top:20px; }
  .panel-body:not(.two-col) { padding:0px }
  .glyphicon { margin-right:5px; }
  .glyphicon-new-window { margin-left:5px; }
  .panel-body .radio,.panel-body .checkbox {margin-top: 0px;margin-bottom: 0px;}
  .panel-body .list-group {margin-bottom: 0;}
  .margin-bottom-none { margin-bottom: 0; }
  .panel-body .radio label,.panel-body .checkbox label { display:block; }
</style>

<?php
  include ('Poll.php');
  $poll = new Poll();
  $voted = 0;
  $pollData = $poll->getPoll();
  if(isset($_POST['vote'])){
    $pollVoteData = array(
      'id' => $_POST['id'],
      'pollOptions' => $_POST['options']
    );
    
    $isVoted = $poll->updateVote($pollVoteData);
    if($isVoted){
      setcookie($_POST['id'], 1, time()+60*60*24*365);
      $voted = 1;
    } else {
      $voted = 2;
    }
  }
  ?>

<div class="container">

<div class="row">
      <?php if(!empty($voted) && $voted === 1) {
        echo '<div class="alert alert-success">Your have voted successfully.</div>';
      }
      else if(!empty($voted)  &amp;&amp; $voted === 2) {
        echo '<div class="alert alert-danger">Your had already voted.</div>';
      }
      ?>
     <form action="" method="post" name="pollForm">
      <?php foreach($pollData as $poll){
        $pollOptions = explode("||||", $poll['options']);?>

	<div class="col-md-3">

	<div class="panel panel-primary">

	<div class="panel-heading">

	<h3 class="panel-title">
		<span class="glyphicon glyphicon-arrow-right"></span><?php echo $poll['question']?><span class="glyphicon glyphicon-new-window"></span>
	</h3>

</div>


<div class="panel-body">

<ul class="list-group">
                <?php for( $i = 0; $i < count($pollOptions); $i++ ) { ?>


 	<li class="list-group-item">

<div class="radio">
                      <label>
                        <input type="radio" name="options" value="<?php echo $i; ?>">
                        <?php echo $pollOptions[$i]?>
                      </label>
</div>

</li>

                <?php }?>

</ul>

</div>


<div class="panel-footer">
              <input type="hidden" name="id" value="<?php echo $poll['id']; ?>">
              <button type="submit" class="btn btn-primary btn-sm" id="vote" name="vote">
              Vote</button>
              <a href="results.php?pollID="<?php echo $poll['id'];?>">View Result</a></div>

</div>

</div>

        <?php }?>
      </form>
</div>

Included bootstrap css file at the top of the file, that help to create beautiful poll widget,The getPoll() method used to get all polls available into database.

We are using php cookie to identify the user has been voted or not, You can use other mechanism as well to identify user session.The ‘View Result’ anchor tag redirect user to result page.

We will create poll.php file and add below code into this file:

<?php
class Poll{
private $host = 'localhost';
private $user = 'root';
private $password = '';
private $database = 'test';
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, MYSQLI_ASSOC)) {
$data[]=$row;
}
return $data;
}
public function getPoll(){
$sqlQuery = 'SELECT id, question, options, votes, voters FROM '.$this->pollTable;
return $this->getData($sqlQuery);
}
public function getVotes($id){
$sqlQuery = 'SELECT votes, voters FROM '.$this->pollTable.' where id = '.$id;
$result = mysqli_query($this->dbConnect, $sqlQuery);
return mysqli_fetch_array($result, MYSQLI_ASSOC);
}
public function updateVote($pollVoteData) {
if(!isset($pollVoteData['id']) || isset($_COOKIE[$pollVoteData['id']])) {
return false;
}
$pollVoteDetails = $this->getVotes($pollVoteData['id']);
$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 id = '".$pollVoteData['id']."'";
mysqli_query($this->dbConnect, $sqlQuery);
return true;
}
}
?>

Defined db credential with test database name to connect mysql database using php, we have defined methods to access polls data and result.

we will create results.php file and added below code:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <style type="text/css">
  
</style>


<?php
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($poll['voters'])="" if(!empty($votes[$i]))="" $votepercent.'%':="" '0%';="" }="" echo="" '<h5="">'.$pollOptions[$i].'';
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>
';
}
}
?>

Included bootstrap css file and get poll results from poll.php class method, after that iterate on poll results and bind with bootstrap progress bar element.

Leave a Reply

Your email address will not be published.