×


Polling System using PHP, MySQL and Ajax

In this article, we introduce a 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 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

First, we created a MySQL table 'tutorial' and inserted some records into the database. You can use the records if you already have them; otherwise, you can create them 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 in the browser. In this file, we have written ajax code that calls 'updatedata.php' file dynamically when a user presses 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 the 'updatedata.php' file, we have written code to update the polling counts on the database and accordingly show 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

How to create search filter in PHP
jquery sticky header on scroll
Bootstrap modal popup on page load
PHP Web Scraping
Ajax live data search using jQuery PHP MySQL
Fetch data from database in PHP and display
How to insert image in database using PHP
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
Remove duplicates from array PHP
Add google reCAPTCHA v2 in registration form using PHP
PHP calculate percentage of total
Generate a PDF file using mPDF in PHP
Insert image in database using PHP




Read more articles


General Knowledge



Learn Popular Language