Voting Functionality in a website

Voting Functionality in a website

In this post I will give the step by step explanation of how we can add Voting Functionality to a website. At the end of this article we will have a working sample voting application. The source code for the sample voting application can be downloaded from here.

We will be using PHP, MySQL, jQuery, HTML, CSS, AJAX to implement this.

To setup this functionality we will have to first setup database, then a front-end and also a page which would actually record and retrieve the votes.

Step 1: Setup Database: We can have a table with following schema:

CREATE TABLE `votes` (
  `vote_id` INT NOT NULL AUTO_INCREMENT ,
  `item_id` INT NOT NULL ,
  `user_id` INT NOT NULL ,
  `datetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
  `ipaddress` INT( 10 ) NOT NULL ,
PRIMARY KEY ( `vote_id` )
) ENGINE = MYISAM ;

Description of the fields of the table:

  • vote_id – Auto-increment count of votes.
  • item_id – ID of the item on which voting is being done, e.g. an article or a picture. In these cases the item_id can be article_id or picture_id respectively.
  • user_id – The user_id of the user who is voting. This field can be used to track which user has voted how many times.
  • datetime – The time-stamp at which the vote was recorded.
  • ipaddress – The ipaddress of the user who has voted. This field is optional, depending on use. I have added this so that I can restrict number of votes from same ipaddress.

We can also have an option store different kinds of votes e.g. likes and dislikes. For this, we will need to add another field in the votes table to indicate the type of vote.

We can use the following SQL statement to add that field to the above table.

ALTER TABLE `votes`
ADD `vote_type` ENUM( 'like', 'dislike' )
NOT NULL DEFAULT 'like' ;
Step 2: Front-end setup: On the webpage we will require a button which can be clicked in-order to vote.

For vote button we will an image and handle its onclick event using JavaScript or jQuery. We can also use some text instead of image.

CSS

#vote_button { background: url('vote.png') no-repeat scroll 0 0 transparent; cursor: pointer; height: 25px; width: 95px; }
#vote_count { padding: 8px 0pt 0pt 30px; }

HTML

<!-- Div for vote button and number of votes -->
<div id="vote_already" style="display: none;">Your have already voted.</div>
<pre></pre>
<div id="vote_recorded" style="display: none;">Thanks for your vote!</div>

The above HTML code will display the vote button and vote count. You should replace ‘vote.png’ with the path of the vote image you want to use. Also, you may have to adjust the CSS of vote_button and vote_count according to your requirements.

Step 3: Handling the vote_button onclick event: In order to record the vote we will have to handle the click even on it. We can use JavaScript or jQuery for it.Using jQuery:

$("#vote_button").click(function()
{
    // Code for handling the click event.
});

Note: If you are using jQuery you will have to include the jQuery library. You can host the jQuery library on your website or use some already hosted file like Google Library API. Use the following code to include the jQuery library

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
Step 4: Recording Votes: To record votes we have various options. We can just reload the page and record the vote or we can use AJAX to record the vote. Using AJAX is a better option because the user would not have to wait until the page is reloaded. It also increases the user experience. We will have to pass some data to a page on the server which would record the vote and respond whether the vote has been recorded successfully or not and updated vote count. Let us use a PHP page on the server-side called “ajax_vote.php”.The AJAX request:

$("#vote_button").click(function()
{
	var item_id = 1;	// This is the item_id for which the number of votes are to be displayed.
	var user_id = 1;	// This is the user_id who is voting.
	var ajax_data = "query=vote&amp;item_id=" + item_id + "&amp;user_id=" + user_id;
	$.ajax({
		type: "GET",
		url: "vote.php",
		data: ajax_data,
		dataType: "html",
		success: function(votecount){
			if(votecount == -1){
				// The user has already voted.
				$("#vote_recorded").css({ display:'none' });
				$("#vote_already").css({ display:'' });
			}
			else
			{
				// Vote recorded, display the updated count.
				$("#vote_already").css({ display:'none' });
				$("#vote_count").html(votecount);
				$("#vote_recorded").css({ display:'' });
			}
		}
	});
});

Note: I am using jQuery AJAX method because it’s very easy to use. Alternatively you can use JavaScript for AJAX.

Step 5: Handling the AJAX request on Server: Now we have the database and front-end completed. We just have to handle the requests on the server and send the response. So now we will write the code in the “ajax_vote.php” file.

// $con is the connection variable to the database
if($_GET['query'] == 'vote')
{
	$item_id = $_GET['item_id'];
	$user_id = $_GET['user_id'];
	$ip_addr = $_SERVER['REMOTE_ADDR'];
	// Check for entry in Database to see if the user has already voted
	$sql = "SELECT vote_id FROM votes WHERE ipaddress = ". ip2long($ip_addr) . " AND user_id = " . $user_id ." AND item_id = " . $item_id . " LIMIT 1";
	$votes = mysql_query($sql, $con);
	$already_voted = false;
	while ($row = mysql_fetch_array($votes))
	{
		$already_voted = true;
	}
	if($already_voted)
	{
		echo -1;
	}
	else
	{
		$sql = "INSERT INTO votes (item_id, user_id, ipaddress) VALUES (" . $item_id . ", ". $user_id . ", ". ip2long($ip_addr) . ")";
		mysql_query($sql, $con);
		// Get updated vote count.
		$total_votes = 0;
		$total_votes = mysql_query("SELECT COUNT(vote_id) as total FROM votes WHERE item_id = ". $item_id . " LIMIT 1", $con);
		while($row = mysql_fetch_array($total_votes))
		{
			echo $row['total'];
		}
	}
}
else if($_GET['query'] == 'votecount')
{
	$item_id = $_GET['item_id'];
	$total_votes = 0;
	$total_votes = mysql_query("SELECT COUNT(vote_id) as total FROM votes WHERE item_id = ". $item_id . " LIMIT 1", $con);
	while($row = mysql_fetch_array($total_votes))
	{
		echo $row['total'];
	}
}

The above code will record the vote and send a response whether the vote has been recorded or not and the updated count. if we et -1 that means the vote was not recorded. Any other value implies the vote was recorded and the value will be equal to the number of votes.

The complete code:

DATABASE Queries:

CREATE TABLE `votes` (
    `vote_id` INT NOT NULL AUTO_INCREMENT ,
    `item_id` INT NOT NULL ,
    `user_id` INT NOT NULL ,
    `datetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `ipaddress` INT( 10 ) NOT NULL ,
    PRIMARY KEY ( `vote_id` )
) ENGINE = MYISAM ;

// If we use this we will have to change the queries in the PHP file. Also will have to change the data passed to the file via ajax.

ALTER TABLE `votes`
ADD `vote_type` ENUM( 'like', 'dislike' )
NOT NULL DEFAULT 'like' ;

CSS CODE:

#vote_button { background: url('vote.png') no-repeat scroll 0 0 transparent; cursor: pointer; height: 25px; width: 95px; }
#vote_count { padding: 8px 0pt 0pt 30px; }

HTML CODE:

<!-- Div for vote button and number of votes -->
<div id="vote_already" style="display: none;">Your have already voted.</div>
<pre></pre>
<div id="vote_recorded" style="display: none;">Thanks for your vote!</div>
<pre>

JavaScript/jQuery CODE:

$(document).ready(function()
{
	// Display number of votes for this item on page load.
	var item_id = 1;	// This is the item_id for which the number of votes are to be displayed.
	var ajax_data1 = "query=votecount&amp;item_id=" + item_id;
	jQuery.ajax({
		type: "GET",
		url: "vote.php",
		data: ajax_data1,
		dataType: "html",
		success: function(html){
			jQuery("#vote_count").html(html);
	   }
	});
});
$("#vote_button").click(function()
{
	var item_id = 1;	// This is the item_id for which the number of votes are to be displayed.
	var user_id = 1;	// This is the user_id who is voting.
	var ajax_data = "query=vote&amp;item_id=" + item_id + "&amp;user_id=" + user_id;
	$.ajax({
		type: "GET",
		url: "vote.php",
		data: ajax_data,
		dataType: "html",
		success: function(votecount){
			if(votecount == -1){
				// The user has already voted.
				$("#vote_recorded").css({ display:'none' });
				$("#vote_already").css({ display:'' });
			}
			else
			{
				// Vote recorded, display the updated count.
				$("#vote_already").css({ display:'none' });
				$("#vote_count").html(votecount);
				$("#vote_recorded").css({ display:'' });
			}
		}
	});
});

PHP CODE:

// $con is the connection variable to the database
if($_GET['query'] == 'vote')
{
	$item_id = $_GET['item_id'];
	$user_id = $_GET['user_id'];
	$ip_addr = $_SERVER['REMOTE_ADDR'];
	// Check for entry in Database to see if the user has already voted
	$sql = "SELECT vote_id FROM votes WHERE ipaddress = ". ip2long($ip_addr) . " AND user_id = " . $user_id ." AND item_id = " . $item_id . " LIMIT 1";
	$votes = mysql_query($sql, $con);
	$already_voted = false;
	while ($row = mysql_fetch_array($votes))
	{
		$already_voted = true;
	}
	if($already_voted)
	{
		echo -1;
	}
	else
	{
		$sql = "INSERT INTO votes (item_id, user_id, ipaddress) VALUES (" . $item_id . ", ". $user_id . ", ". ip2long($ip_addr) . ")";
		mysql_query($sql, $con);
		// Get updated vote count.
		$total_votes = 0;
		$total_votes = mysql_query("SELECT COUNT(vote_id) as total FROM votes WHERE item_id = ". $item_id . " LIMIT 1", $con);
		while($row = mysql_fetch_array($total_votes))
		{
			echo $row['total'];
		}
	}
}
else if($_GET['query'] == 'votecount')
{
	$item_id = $_GET['item_id'];
	$total_votes = 0;
	$total_votes = mysql_query("SELECT COUNT(vote_id) as total FROM votes WHERE item_id = ". $item_id . " LIMIT 1", $con);
	while($row = mysql_fetch_array($total_votes))
	{
		echo $row['total'];
	}
}
Click here to download a sample voting application.
Update: Here are the screenshots of how the sample application would look.

Initial: This is how the page would look initially.

After voting for the first time: When you vote for the first time you will see the following.

Trying to revote: If you have already voted, and you try to vote again, you will get the following:

Trying to revote

Note: I have tested the above steps on Wampserver 2.1 using PHP 5.3.4, MySQL 5.1.53, Apache 2.2.17. Also, I have used jQuery 1.5.1 from google APIs. Having said that I do not take responsibility for proper functioning of the above mentioned steps under all circumstances. If you download any files, programs from my blog then make sure you protect yourself. I am not responsible for any damage to your computer, website, blog, application or any thing else.
  1. hi can you implement this in opencart?

  2. Questions I Havvve

    How would I put this on a website?

Leave a Reply