Skip to main content

Dynamic Voting System with jQuery, PHP and MySQL

In this post you will learn how to build a voting system with jQuery, Ajax, PHP and MySQL. Votes will be update at real time and store to the database table with out refreshing or redirecting page. This post is inspired by Reddit and Stack Overflow voting system. This system will allow users to vote up or vote down every single post at once in a session.

Live Demo Download Source

Database Design

At first we need to create a database table called voting. Actually this table stores all information like post contents and voting information.

  `first_name` varchar(45) NOT NULL,
  `last_name` varchar(45) NOT NULL,
  `film_info` text NOT NULL,
  `vote` int(8) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)

Database Configurations and Connection

This configuration file is responsible for making DB connection. You need to do little bit modify it.

# db configurations
define('DB_HOST',    'localhost');
define('DB_USER',    'root');
define('DB_PASS',    'root');
define('DB_NAME',    'mydb');

# db connect
function dbConnect($close=true){
  global $link;

  if (!$close) {
    return true;

  $link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('Could not connect to MySQL DB ') . mysql_error();
  if (!mysql_select_db(DB_NAME, $link))
    return false;

PHP & HTML (Retrieve DB Recodes)

# connect mysql db
$query = mysql_query(
  'SELECT id, first_name, last_name, film_info, vote 
  FROM  voting
  LIMIT 0 , 15');
<!doctype html>
<html lang="en">
  <meta charset="UTF-8" />
  <title>jQUery Voting System</title>
  <div class="wrap">
    <?php while($row = mysql_fetch_array($query)): ?>
    <div class="item" data-postid="<?php echo $row['id'] ?>" data-score="<?php echo $row['vote'] ?>">
      <div class="vote-span"><!-- voting-->
        <div class="vote" data-action="up" title="Vote up">
          <i class="icon-chevron-up"></i>
        </div><!--vote up-->
        <div class="vote-score"><?php echo $row['vote'] ?></div>
        <div class="vote" data-action="down" title="Vote down">
          <i class="icon-chevron-down"></i>
        </div><!--vote down-->

      <div class="post"><!-- post data -->
        <h2><?php echo $row['first_name'].' '.$row['last_name']?></h2>
        <p><?php echo $row['film_info'] ?></p>
    <?php endwhile?>
  <?php dbConnect(false); ?>


We need to do some styling for post contents and vote buttons. In here, I used Font Awesome for style up vote up and down buttons. If you want you can use image background as you like.

/* voting style */
  width: 60px;
  float: left;
  margin: 5px 0;
.vote, .vote-score{
  clear: both;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  text-align: center;
  color: #333;
  font-size: 1.8em;
  font-weight: bold;
.vote-score{cursor: text}


<script src=""></script>
  // ajax setup
    url: 'ajaxvote.php',
    type: 'POST',
    cache: 'false'

  // any voting button (up/down) clicked event
    var self = $(this); // cache $this
    var action ='action'); // grab action data up/down 
    var parent = self.parent().parent(); // grab grand parent .item
    var postid ='postid'); // grab post id from data-postid
    var score ='score'); // grab score form data-score

    // only works where is no disabled class
    if (!parent.hasClass('.disabled')) {
      // vote up action
      if (action == 'up') {
        // increase vote score and color to orange
        // change vote up button color to orange
        // send ajax request with post id & action
        $.ajax({data: {'postid' : postid, 'action' : 'up'}});
      // voting down action
      else if (action == 'down'){
        // decrease vote score and color to red
        // change vote up button color to red
        // send ajax request
        $.ajax({data: {'postid' : postid, 'action' : 'down'}});

      // add disabled class with .item


# start new session
  if (isset($_POST['postid']) AND isset($_POST['action'])) {
    $postId = (int) mysql_real_escape_string($_POST['postid']);
    # check if already voted, if found voted then return
    if (isset($_SESSION['vote'][$postId])) return;
    # connect mysql db

    # query into db table to know current voting score 
    $query = mysql_query("
      SELECT vote
      from voting
      WHERE id = '{$postId}' 
      LIMIT 1" );

    # increase or dicrease voting score
    if ($data = mysql_fetch_array($query)) {
      if ($_POST['action'] === 'up'){
        $vote = ++$data['vote'];
      } else {
        $vote = --$data['vote'];
      # update new voting score
        UPDATE voting
        SET vote = '{$vote}'
        WHERE id = '{$postId}' ");

      # set session with post id as true
      $_SESSION['vote'][$postId] = true;
      # close db connection

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery . Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar. We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin . It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code . multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.