PHP Poll Script

by Vincy. Last modified on July 5th, 2023.

In this tutorial, we will learn how to create a poll script for rating using PHP. In a previous tutorial, we have seen PHP star rating using jQuery.

In this example poll script, there are questions with multiple options to add user ratings in a poll. After submitting the poll rating, the overall rating percentage for all the options will be shown to the users.

In this script, I have used jQuery AJAX to show set poll options and save user poll options into the backend database tables. The user session id is defined in the beginning, and the poll rating is saved into the database for the user session.

View Demo

On clicking next, the next unrated question will be shown to the user.

The following screenshots show the poll options and ratings.

poll-options

poll-rating

Set Poll Options to Add Rating

In this section, we will read questions and poll options from the database to show them for user rating. I send an AJAX call to the PHP script to get a question the user does not yet rate.

This script will respond to the poll HTML to the user to submit their rating. The jQuery AJAX and the PHP script is shown below.

function show_poll(){
	$.ajax({
		type: "POST", 
		url: "show-poll.php", 
		processData : false,
		beforeSend: function() {
			$("#overlay").show();
		},
		success: function(responseHTML){
			$("#overlay").hide();
			$("#poll-content").html(responseHTML);
		}
	});
}

show-poll.php

<?php
    session_start();
    $_SESSION["member_id"] = 1;
    
	require("dbcontroller.php");
	$dbController = new DBController();
	
	$query = "SELECT DISTINCT question_id from tbl_poll WHERE member_id = " . $_SESSION["member_id"]; 
	$result = $dbController->getIds($query);
	
	$condition = "";
	if(!empty($result)) {
	    $condition = " WHERE id NOT IN (" . implode(",", $result) . ")";
    }
    
    $query = "SELECT * FROM `tbl_question` " . $condition . " limit 1";
    $questions = $dbController->runQuery($query);
    
    if(!empty($questions)) {
?>      
		<div class="question"><?php echo $questions[0]["question"]; ?><input type="hidden" name="question" id="question" value="<?php echo $questions[0]["id"]; ?>" ></div>      
<?php 
        $query = "SELECT * FROM tbl_answer WHERE question_id = " . $questions[0]["id"];
        $answers = $dbController->runQuery($query);
        if(!empty($answers)) {
            foreach($answers as $k=>$v) {
                ?>
			<div class="question"><input type="radio" name="answer" class="radio-input" value="<?php echo $answers[$k]["id"]; ?>" /><?php echo $answers[$k]["answer"]; ?></div>      
<?php 
            }
        }
?>
		<div class="poll-bottom">
			<button id="btnSubmit" onClick="addPoll()">Submit</button>
		</div>
<?php        
    } else {
?>
<div class='error'>No Questions Found</div>
<?php 
    }
?>

Save Rating using jQuery AJAX

In this section, I receive the user rating and send it to the PHP script to update the rating database. On submitting the poll rating, it invokes the jQuery AJAX function to request PHP to update the rating.

After updating the rating table, the response will show the overall rating in percentage. The PHP and AJAX code is,

function addPoll() {
	if($("input[name='answer']:checked").length != 0){
		var answer = $("input[name='answer']:checked").val();
		$.ajax({
			type: "POST", 
			url: "save-poll.php", 
			data : "question="+$("#question").val()+"&answer="+$("input[name='answer']:checked").val(),
			processData : false,
			beforeSend: function() {
				$("#overlay").show();
			},
			success: function(responseHTML){
				$("#overlay").hide();	
				$("#poll-content").html(responseHTML);				
			}
		});
			
	}
}

save-poll.php

<?php
    session_start();
    require("dbcontroller.php");
	$dbController = new DBController();
	
	$answer_id  = $_POST['answer'];
	$question_id = $_POST['question'];
	
	$query = "INSERT INTO tbl_poll(question_id,answer_id,member_id) VALUES ('" . $question_id ."','" . $answer_id . "','" . $_SESSION["member_id"] . "')";
    $insert_id = $dbController->insertQuery($query);
    
    if(!empty($insert_id)) {
        $query = "SELECT * FROM tbl_answer WHERE question_id = " . $question_id;
        $answer = $dbController->runQuery($query);
    }
    
    if(!empty($answer)) {
?>        
        <div class="poll-heading"> Rating </div> 
<?php
        $query = "SELECT count(answer_id) as total_count FROM tbl_poll WHERE question_id = " . $question_id;
        $total_rating = $dbController->runQuery($query);

        foreach($answer as $k=>$v) {
            $query = "SELECT count(answer_id) as answer_count FROM tbl_poll WHERE question_id = " .$question_id . " AND answer_id = " . $answer[$k]["id"];
            $answer_rating = $dbController->runQuery($query);
            $answers_count = 0;
            if(!empty($answer_rating)) {
                $answers_count = $answer_rating[0]["answer_count"];
            }
            $percentage = 0;
            if(!empty($total_rating)) {
                $percentage = ( $answers_count / $total_rating[0]["total_count"] ) * 100;
                if(is_float($percentage)) {
                    $percentage = number_format($percentage,2);
                }
            }
            
?>
		<div class="answer-rating"> <span class="answer-text"><?php echo $answer[$k]["answer"]; ?></span><span class="answer-count"> <?php echo $percentage . "%"; ?></span></div>      
<?php 
        }
    }
?>
<div class="poll-bottom">
	<button class="next-link" onClick="show_poll();">Next</button>
</div>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page