Online Voting System with PHP & MySQL

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.
online voting system with php & mysql

Create Database:

Create Table:

Config.php:

Above code has PHP PDO connection in try and catch block. I also set an attribute for error exception.

Functions.php:

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

First of all index file include 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.


 

Posted in PHP

Leave a Reply

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