etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Polling System using PHP, MySQL and Ajax

In this article, we introduce very simple polling/ voting system using PHP, MySQL and Ajax. It helps us to securely and easily conduct online web based elections or votes. We can also display the result on the same page for every vote. We have used the ajax to retrieve the voting data without reloading the whole web page. We have used the MySQL database to store the voting details.

Polling system using PHP, Ajax and MySql

For this, first we have created a MySQL table name 'tutorial' and inserted some records in database. You can use the records if you already have otherwise you can create it manually or copy and paste the following queries in your database.

CREATE TABLE IF NOT EXISTS `tutorial` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tutorial` varchar(100) NOT NULL,
  `count` int(11) NOT NULL,
  `is_enabled` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) 


INSERT INTO `tutorial` (`id`, `tutorial`, `count`, `is_enabled`) VALUES
(1, 'PHP', 3, 1),
(2, 'Java', 34, 1),
(3, 'Dot Net', 13, 1);



Here, we have written database connection code in 'config.php' file, make sure to replace the 'host_name', 'user_name', 'password' and 'db_name' with your database configurations.

1. config.php
<?php
 // config.php 
 $hostname = "host_name";
 $username = "user_name";
 $password = "password";
 $database = "db_name";
 $conn = mysqli_connect($hostname, $username, $password, $database) or die("Could not connect database"); 
 ?>

This is the main file, that we will call on the browser. In this file, we have written ajax code that calls 'updatedata.php' file dynamically when user pressed on any polling option.

2. index.php
<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            .container{ border: 1px solid black; background-color: #66ff99; padding: 10px; }
            #showvotebar { margin-top: 20px;}
        </style>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript">
            function countvalue($val){
                $.ajax({
                    type: 'POST',
                    url: 'updatedata.php', //call storeemdata.php to store form data
                    data: { 
                    val: $val
                    },
                    success: function(response ) { 
                        var ajaxDisplay = document.getElementById('showvotebar');
                        ajaxDisplay.innerHTML = response;
                    }
                });
            }
        </script>
    </head>
    <body>
        <center>
            <div class="container">
            <?php
            include('config.php');
            $mysql_query = "SELECT * FROM tutorial WHERE is_enabled = '1' ";
            $result = mysqli_query($conn, $mysql_query);
            while($row = mysqli_fetch_array($result)) {
                ?>
                <button name="vote" onclick="countvalue(this.value)" value="<?php echo $row['id']; ?>"  class="btn btn-primary">
                    <?php echo '<b>'.$row['tutorial'].'</b>'; ?>
                </button>
                <?php
            }
            ?>
            <div id="showvotebar">
                <?php 
                $data = array('progress-bar-danger', 'progress-bar-warning', 'progress-bar-info');
                $total = '';
                $result= mysqli_query($conn, "SELECT * from tutorial where is_enabled ='1'");
                while($row = mysqli_fetch_array($result)){
                    $total = $total + $row[2];
                } 
                $i = 0;
                $result = mysqli_query($conn, "SELECT * from tutorial where is_enabled ='1'");
                while($row = mysqli_fetch_array($result)){ 
                    $percentage = ($row[2] / $total) * 100;
                    echo '<div class="progress">';
                    echo '<div class="progress-bar '.$data[$i].'" role="progressbar" aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width:'.$percentage.'%">';
                    echo $row[1].'('.round($percentage).')';
                    echo '</div>';
                    echo '</div>';
                    $i++;
                }
                ?>
            </div>
        </center>
    </body>
</html>



In 'updatedata.php' file, we have written code to update the polling counts on the database and accordingly shows the polling progress bar on the system.

3. updatedata.php
<?php
include("config.php");
if($_POST['val'])
{
    $id = $_POST['val']; 
    $newcout = '3';
    $result = mysqli_query($conn, "SELECT * from tutorial where id= '$id' AND is_enabled ='1'");
    $row = mysqli_fetch_row($result);
    $count = $row[2]+1;
    $update = "UPDATE `tutorial` SET `count` = '$count' WHERE `id` = '$id' ";
    if(mysqli_query($conn, $update)){
        $total = '';
        $result= mysqli_query($conn, "SELECT * from tutorial where is_enabled ='1'");
        while($row = mysqli_fetch_array($result)){
            $total = $total + $row[2];
        }
        $i = 0;
        $data = array('progress-bar-danger', 'progress-bar-warning', 'progress-bar-info');
        $result=mysqli_query($conn, "SELECT * from tutorial where is_enabled ='1'");
        while($row=mysqli_fetch_array($result)){
            $percentage = ($row[2] / $total) * 100;
            echo '<div class="progress">';
            echo '<div class="progress-bar '.$data[$i].'" role="progressbar" aria-valuenow="'.$percentage.'" aria-valuemin="0" aria-valuemax="100" style="width:'.$percentage.'%">';
            echo $row[1].'('.round($percentage).')';
            echo '</div>';
            echo '</div>';
            $i++;
        }
    }
}
?>




Related Articles

Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
Characteristics of a Good Computer Program
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
PHP Create Word Document from HTML
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
How to encrypt password in PHP
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Simple pagination in PHP with MySQL
-----------------
Fibonacci Series Program in PHP
-----------------
How to add multiple custom markers on google map
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
Php file based authentication
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Polling system using PHP, Ajax and MySql
-----------------
How to generate QR Code in PHP
-----------------
SQL Injection Prevention Techniques
-----------------
Simple File Upload Script in PHP
-----------------
PHP User Authentication by IP Address
-----------------
Calculate the distance between two locations using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
To check whether a year is a leap year or not in php
-----------------
CSS Simple Menu Navigation Bar
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Server Side Form Validation
-----------------
Simple way to send SMTP mail using Node.js
-----------------
Set and Get Cookies in PHP
-----------------
Date Timestamp Formats in PHP
-----------------
Get Visitor\'s location and TimeZone
-----------------
Convert MySQL to JSON using PHP
-----------------
Simple Show Hide Menu Navigation
-----------------
PHP Sending HTML form data to an Email
-----------------
PHP Programming Error Types
-----------------
How to print specific part of a web page in javascript
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Google Street View API Example
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
PHP Getting Document of Remote Address
-----------------
PHP Connection and File Handling on FTP Server
-----------------
File Upload Validation in PHP
-----------------
R Plot Types
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2021. All Rights Reserved.