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




Read more articles


General Knowledge



Learn Popular Language