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.
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' ;
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.
$("#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>
$("#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&item_id=" + item_id + "&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.
// $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.
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&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&item_id=" + item_id + "&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']; } }
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:
Thanks for sharing.
hi can you implement this in opencart?
How would I put this on a website?
thanks for this code