Online voting system is one of the best way to get user opinion about any topic. Now a days, most of the news and sports sites usually have this system.
So in this tutorial I am going create an online voting system using PHP and MySQL with IP restriction. I will use the example of top football player.
Voting System with PHP & MySQL:
This system will have 3 files which are:
- Config.php:File having MySQL database connection
- Functions.php: This file will have custom PHP functions which will fetch result/count from MySQL database.
- Index.php: This file will have HTML and PHP section. At the top of the file there will be PHP Code. After PHP code there will be HTML code for polling question and its result. Also I will be using bootstrap 4 for styling.
Create Database:
1 2 3 |
Create database demo; |
Create Table:
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE `footballer_poll` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `footballer_name` VARCHAR(100) NULL DEFAULT NULL, `user_ip` VARCHAR(50) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=1; |
Config.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php $dsn = 'mysql:dbname=demo;host=localhost'; $user = 'root'; $password = ''; try { $pdo = new PDO($dsn,$user,$password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "PDO error".$e->getMessage(); die(); } ?> |
Above code has PHP PDO connection in try and catch block. I also set an attribute for error exception.
Functions.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php function getAllResults() { global $pdo; $sql = 'select count(id) as total from footballer_poll'; $handle = $pdo->prepare($sql); $handle->execute(); $count = $handle->fetch(PDO::FETCH_ASSOC); return $count['total']; } function getResultByName($name) { global $pdo; $sql = 'select count(id) as total from footballer_poll where footballer_name = :name '; $handle = $pdo->prepare($sql); $param = ['name' => $name]; $handle->execute($param); $count = $handle->fetch(PDO::FETCH_ASSOC); return $count['total']; } function getSinglePlayerData($playerName){ global $pdo; $getAllCount = getAllResults(); $getPlayerCount = getResultByName($playerName); $calculate = $getPlayerCount/$getAllCount * 100; return number_format($calculate,2,)."%"; } function ifIPIsExist($ip){ global $pdo; $sql = 'select * from footballer_poll where user_ip = :ip '; $handle = $pdo->prepare($sql); $param = ['ip' => $ip]; $handle->execute($param); return ($handle->rowCount() > 0) ?? TRUE; } ?> |
As you can see in above code I have written 4 functions. Each function have global $pdo
that will get the value (in our case db object) of $pdo
from global namespace. getAllResults()
returns total count of vote. getResultByName()
functions returns count of specific footballer. getSinglePlayerData()
returns the percentage of vote against specific player and ifIPIsExist
checks the IP address of current user. If current already vote with current IP then it will return 1 otherwise empty.
Index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
<?php require_once('config.php'); require_once('functions.php'); if(isset($_POST['submit'])) { if(isset($_POST['footballer']) && !empty($_POST['footballer'])) { $footballerName = $_POST['footballer']; $clientIP = $_SERVER['REMOTE_ADDR']; $checkIfIpExist = ifIPIsExist($clientIP); if($checkIfIpExist == 1) { $errorMsg = 'You already cast your vote.'; } else { $sql = 'insert into footballer_poll (footballer_name,user_ip) values(:name,:ip)'; $handle = $pdo->prepare($sql); $params = [ 'name' => $footballerName, 'ip' =>$clientIP ]; $handle->execute($params); if($handle->rowCount()) { $successMsg = 'Thank you! For your vote'; } else { $errorMsg = 'Unable to save your vote. Try again later'; } } } else { $errorMsg = 'Please pick one footballer'; } } $ronaldoCount = getSinglePlayerData('Cristiano Ronaldo'); $messiCount = getSinglePlayerData('Lionel Messi '); $neymarCount = getSinglePlayerData('Neymar'); $salahCount = getSinglePlayerData('Muhammad Salah'); ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Demo - Online Voting System with php and MySQL</title> </head> <body > <div class="container mt-1 p-3 text-center"> <h1>Online Voting System with PHP MySQL</h1> </div> <div class="container mt-1 p-3 border"> <h2>Vote for Best Footballer:</h2> <?php if(isset($errorMsg)) { echo '<div class="alert alert-danger">'.$errorMsg.'</div>'; } if(isset($successMsg)) { echo '<div class="alert alert-success">'.$successMsg.'</div>'; } ?> <form class="" method="post" action="<?php $_SERVER['PHP_SELF']?>"> <div class="row "> <div class="col-md-6 "> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="footballer1" name="footballer" value="Cristiano Ronaldo"> <label class="custom-control-label" for="footballer1">Cristiano Ronaldo</label> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="footballer2" name="footballer" value="Lionel Messi"> <label class="custom-control-label" for="footballer2">Lionel Messi</label> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="footballer3" name="footballer" value="Neymar"> <label class="custom-control-label" for="footballer3">Neymar</label> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="footballer4" name="footballer" value="Muhammad Salah"> <label class="custom-control-label" for="footballer4">Muhammad Salah </label> </div> </div> </div> <div class="row"> <div class="col-md-6 pt-2"> <button type="submit" name="submit" class="btn btn-danger">Vote</button> </div> </div> </form> </div> <div class="container mt-3 border p-3"> <h2>Result: Vote for Best Footballer</h2> <div class="row"> <div class="col-md-2">Cristiano Ronaldo</div> <div class="col-md-6"> <div class="progress mb-2"> <div class="progress-bar progress-bar-striped progress-bar-animated" style="width:<?php echo $ronaldoCount?>"><?php echo $ronaldoCount?></div> </div> </div> </div> <div class="row"> <div class="col-md-2">Lionel Messi </div> <div class="col-md-6"> <div class="progress mb-2"> <div class="progress-bar bg-success progress-bar-striped progress-bar-animated" style="width:<?php echo $messiCount?>"><?php echo $messiCount?></div> </div> </div> </div> <div class="row"> <div class="col-md-2">Neymar</div> <div class="col-md-6"> <div class="progress mb-2"> <div class="progress-bar bg-warning progress-bar-striped progress-bar-animated" style="width:<?php echo $neymarCount?>"><?php echo $neymarCount?></div> </div> </div> </div> <div class="row"> <div class="col-md-2">Muhammad Salah</div> <div class="col-md-6"> <div class="progress mb-2"> <div class="progress-bar bg-danger progress-bar-striped progress-bar-animated" style="width:<?php echo $salahCount?>"><?php echo $salahCount?></div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> </body> </html> |
config.php
and functions.php
. After that there is vote form submit logic with error and success message. I have used $_SERVER['REMOTE_ADDR']
to get current user IP address and match with database IPs.
Note: $_SERVER[‘REMOTE_ADDR’] sometimes may not return correct IP address.