Online polls are mainly used to identify the choice of web users. Online survey or polls is mostly used on the web today, and many services are available that provide a built-in poll system. However, you can easily implement the online voting system using PHP and MySQL. If you want to create your own poll and voting system, this tutorial will help you to create a simple, clean polling or voting system using PHP.
The poll or voting system lets the user share their opinion on a subject by selecting from several options. The system counts all the votes and displays the overall result in percentage. This poll or voting system is often used in market research, surveys, and websites to collect feedback on various topics and understand what people think about them. In this tutorial, we will show you how to build a simple poll script in PHP. The example script uses PHP and MySQL to create a poll system without using any JavaScript or jQuery. Also, this voting script store poll data, poll options, and votes into the database using PHP and MySQL.
Poll and options data is stored in the MySQL database. Poll questions and respective options will be fetched from the database and shown to the user. The user can be able to select an option and submit their vote. Once the vote is submitted, it will be stored in the database with the respective poll option. Also, PHP COOKIE will be used to restrict the user from submitting the vote multiple times. The poll result with the total votes count and votes on each option will be displayed on the result page. The result of the poll’s options will be shown in a percentage bar.
In the example voting script, the following functionality will be implemented.
Before getting started to build online poll & voting system with PHP, take a look at the file structure.
poll_voting_system_with_php/ ├── index.php ├── results.php ├── Poll.class.php └── css/ └── style.css
We will use 3 tables to store polls, options, and voting count in the database.
The following SQL creates a polls
table in the MySQL database, it holds poll subject/question info.
CREATE TABLE `polls` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`subject` text NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a poll_options
table in the MySQL database, it holds options/answers associated with the respective poll.
CREATE TABLE `poll_options` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`poll_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`),
KEY `poll_id` (`poll_id`),
CONSTRAINT `poll_options_ibfk_1` FOREIGN KEY (`poll_id`) REFERENCES `polls` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a poll_votes
table in the MySQL database, it holds the voting count for each poll option.
CREATE TABLE `poll_votes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`poll_id` int(11) NOT NULL,
`poll_option_id` int(11) NOT NULL,
`vote_count` bigint(10) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
KEY `poll_id` (`poll_id`),
KEY `poll_option_id` (`poll_option_id`),
CONSTRAINT `poll_votes_ibfk_1` FOREIGN KEY (`poll_id`) REFERENCES `polls` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `poll_votes_ibfk_2` FOREIGN KEY (`poll_option_id`) REFERENCES `poll_options` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
For the demonstration purpose, insert some test data (poll and respective options) in the database.
INSERT INTO `polls` (`id`, `subject`, `created`, `modified`, `status`) VALUES
(1, 'What is your Favorite Programming Language?', '2024-08-18 04:13:13', '2024-08-18 04:13:13', 1);
INSERT INTO `poll_options` (`id`, `poll_id`, `name`, `created`, `modified`, `status`) VALUES
(1, 1, 'PHP', '2024-08-18 04:13:13', '2024-08-18 04:13:13', 1),
(2, 1, 'Python', '2024-08-18 04:13:13', '2024-08-18 04:13:13', 1),
(3, 1, 'JavaScript', '2024-08-18 04:13:13', '2024-08-18 04:13:13', 1),
(4, 1, 'Java', '2024-08-18 04:13:13', '2024-08-18 04:13:13', 1),
(5, 1, 'C and C++', '2024-08-18 19:39:46', '2024-08-18 19:39:46', 1),
(6, 1, 'Ruby', '2024-08-18 19:39:46', '2024-08-18 19:39:46', 1),
(7, 1, 'Other', '2024-08-18 19:40:25', '2024-08-18 19:40:25', 1);
The Poll class handles the database related operations (connect, select, insert, update, and delete) using PHP and MySQL. Specify the database host ($dbHost
), username ($dbUser
), password ($dbPwd
), and name ($dbName
) as per your database server credentials.
__construct()
– Connect and select the database.getQuery()
– Execute the SQL query and return the respective data. It is a private function used by this class only.getPolls()
– Fetch the poll and respective options. Also, it can fetch multiple poll data based on the request.vote()
– Insert or update the vote count into the database.getResult()
– Get poll results with the voting count of each option.<?php
/*
* Poll Management Class
* This class is used to manage online poll & voting system with PHP
* @author CodexWorld.com
* @url http://www.codexworld.com
* @license http://www.codexworld.com/license
*/
class Poll{
private $dbHost = 'localhost';
private $dbUser = 'root';
private $dbPwd = 'root';
private $dbName = 'codexworld_db';
private $db = false;
private $pollTbl = 'polls';
private $optTbl = 'poll_options';
private $voteTbl = 'poll_votes';
public function __construct(){
if(!$this->db){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUser, $this->dbPwd, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Runs query to the database
* @param string SQL
* @param string count, single, all
*/
private function getQuery($sql,$returnType = ''){
$result = $this->db->query($sql);
if($result){
switch($returnType){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
}
return !empty($data)?$data:false;
}
/*
* Get polls data
* Returns single or multiple poll data with respective options
* @param string single, all
*/
public function getPolls($poll_type = 'single'){
$sql = "SELECT * FROM ".$this->pollTbl." WHERE status = 1 ORDER BY id DESC";
$result = $this->getQuery($sql, $poll_type);
if(!empty($result)){
if($poll_type == 'single'){
$data['poll'] = $result;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$result['id']." AND status = 1";
$opts_result = $this->getQuery($sql2);
$data['options'] = $opts_result;
}else{
$i = 0;
foreach($result as $prow){
$data[$i]['poll'] = $prow;
$sql2 = "SELECT * FROM ".$this->optTbl." WHERE poll_id = ".$prow['id']." AND status = 1";
$opts_result = $this->getQuery($sql2);
$data[$i]['options'] = $opts_result;
}
}
}
return !empty($data)?$data:false;
}
/*
* Insert voting
* @param array of poll option data
*/
public function vote($data = array()){
if(!isset($data['poll_id']) || !isset($data['poll_option_id']) || isset($_COOKIE['poll_voting_id-'.$data['poll_id']])){
return false;
}else{
$sql = "SELECT * FROM ".$this->voteTbl." WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$preVote = $this->getQuery($sql, 'count');
if($preVote > 0){
$query = "UPDATE ".$this->voteTbl." SET vote_count = vote_count+1 WHERE poll_id = ".$data['poll_id']." AND poll_option_id = ".$data['poll_option_id'];
$update = $this->db->query($query);
}else{
$query = "INSERT INTO ".$this->voteTbl." (poll_id,poll_option_id,vote_count) VALUES (".$data['poll_id'].", ".$data['poll_option_id'].", 1)";
$insert = $this->db->query($query);
}
return true;
}
}
/*
* Get poll result
* @param poll ID
*/
public function getResult($poll_id){
if(!empty($poll_id)){
$sql = "SELECT p.subject, SUM(v.vote_count) as total_votes FROM ".$this->voteTbl." as v LEFT JOIN ".$this->pollTbl." as p ON p.id = v.poll_id WHERE poll_id = ".$poll_id;
$result = $this->getQuery($sql, 'single');
if(!empty($result)){
$data['poll'] = $result['subject'];
$data['total_votes'] = $result['total_votes'];
$sql2 = "SELECT o.id, o.name, v.vote_count FROM ".$this->optTbl." as o LEFT JOIN ".$this->voteTbl." as v ON v.poll_option_id = o.id WHERE o.poll_id = ".$poll_id;
$opts_result = $this->getQuery($sql2);
if(!empty($opts_result)){
foreach($opts_result as $row){
$data['options'][$row['name']] = $row['vote_count'];
}
}
}
}
return !empty($data)?$data:false;
}
}
?>
Initially, the poll subject and respective options are displayed. For selecting an option a radio button is placed with each option label. The user can use the submit button to provide their vote. Also, a link will be provided to view the results of the poll.
<?php
// Include and initialize Poll class
include_once 'Poll.class.php';
$pollDB = new Poll();
// Get poll and options data
$poll_data = $pollDB->getPolls();
// If vote is submitted
if(isset($_POST['voteSubmit'])){
if(!empty($_POST['poll_id']) && !empty($_POST['vote_opt'])){
// Insert voting data
$voteData = array(
'poll_id' => $_POST['poll_id'],
'poll_option_id' => $_POST['vote_opt']
);
$voteSubmit = $pollDB->vote($voteData);
if($voteSubmit){
// Store in $_COOKIE to signify the user has voted
setcookie('poll_voting_id-'.$_POST['poll_id'], $_POST['vote_opt'], time()+60*60*24*365);
$status = 'success';
$statusMsg = 'Your vote has been recorded successfully.';
}else{
$status = 'danger';
$statusMsg = 'Your vote has already been submitted!';
}
}else{
$status = 'danger';
$statusMsg = 'Please select an option to vote.';
}
}
// Retrieve existing voting info from COOKIE
if(!empty($_COOKIE['poll_voting_id-'.$poll_data['poll']['id']])){
$ck_poll_option = $_COOKIE['poll_voting_id-'.$poll_data['poll']['id']];
}
?>
<!-- Status message -->
<?php echo !empty($statusMsg)?'<div class="alert alert-'.$status.'">'.$statusMsg.'</div>':''; ?>
<!-- Poll & options -->
<div class="voting-wrap">
<form method="post" action="">
<h3><?php echo $poll_data['poll']['subject']; ?></h3>
<ul>
<?php foreach($poll_data['options'] as $opt){
// Check existing voting option
$opt_select = '';
if(!empty($ck_poll_option) && $ck_poll_option == $opt['id']){
$opt_select = 'checked';
}
echo '<li><input type="radio" name="vote_opt" value="'.$opt['id'].'" '.$opt_select.'>'.$opt['name'].'</li>';
} ?>
</ul>
<input type="hidden" name="poll_id" value="<?php echo $poll_data['poll']['id']; ?>">
<input type="submit" name="voteSubmit" class="btn btn-success" value="Submit Vote">
</form>
</div>
<a href="results.php?poll_id=<?php echo $poll_data['poll']['id']; ?>" class="btn btn-primary">View Results →</a>
On this page, the voting result of the selected poll is fetched from the database and shown to the user. The voting count of all options is listed in percentage format with a progress bar UI.
<?php
// Include and initialize Poll class
include_once 'Poll.class.php';
$pollDB = new Poll();
// Get poll result data
$poll_result = $pollDB->getResult($_GET['poll_id']);
?>
<h3><?php echo $poll_result['poll']; ?></h3>
<p>Total Votes: <b><?php echo $poll_result['total_votes']; ?></b></p>
<?php
// Generate option bars with votes count
if(!empty($poll_result['options'])){ $i=0;
foreach($poll_result['options'] as $opt=>$vote){
$vote_count = !empty($vote)?$vote:0;
$vote_percent = round(($vote_count/$poll_result['total_votes'])*100);
$vote_percent = !empty($vote_percent)?$vote_percent.'%':'0%';
?>
<div class="bar-wrap">
<h4><?php echo $opt; ?> <span>(<?php echo $vote_count; ?> votes</span>)</h4>
<div class="progress">
<div class="progress-bar bg-<?php echo $i; ?>" style="width: <?php echo $vote_percent; ?>;"><?php echo $vote_percent; ?></div>
</div>
</div>
<?php
$i++;
}
}
?>
Here we’ve tried to show the web poll system creation process with PHP and MySQL. Hope this online voting tutorial helps to understand online polling system and build your own web poll using PHP and MySQL. Also, you can easily extend this simple PHP poll and voting system script as per your requirements.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
How to get multiple questions with respective options on the same page or is there any other way to get multiple questions(subject)? Please help
Great it works but how about creating a questions and add multiple choices?
Thanks but how can I code for more than one subject.
Thank You , Grate Tutorial
how to make the index show multiple question instead of single question ? I have made other polls subjects
how best can i prevent different users from casting more than one votes for a specific subject at the same time?
Thank you! but what if i have different subjects like four of them.
In that case, you need to insert these subjects in the “polls” table of the database.
on index page error occurs on line 3 like on this way:
Undefined variable: poll in C:\xampp\htdocs\pooling\index.php on line 3
can anyone solve this error
Probably, you have not initialized the Poll class before using the
$poll
variable.Thank you for such a awesome code, worked like a charm…
Thank you for this. This will helped me a lot
Gerat tuto, I’ll put on my website to Buy and Sell in Cuba. It’s a good idea to know the feedback of my users