Voting

For a company I build this very basic post voting thingy. It it very simple to add to any site I think where there is a userid and a postid (or such) to identify who voted for what .

In the future I think I will expand it to a WordPress plugin with more options. But for now this is it.

You can add a new vote possibility by only adding this line of code where $itemId and $userId have to be filled with data from your own site.

<?php voting::showVote($itemId1, $userId1); ?>

Upload the folder voting to your site and include voting .php in your index.php
For example here are 4 items that the same user can vote for. Of course you should figure out where the itemId and the userId come from on your own site:

<?php
include 'voting/voting.php';
$itemId1 = 1;
$itemId2 = 2;
$itemId3 = 3;
$itemId4 = 4;

$userId1 = 1;
?>

<!DOCTYPE html>
<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    </head>
    <body>
        <br />
        <?php voting::showVote($itemId1, $userId1); ?>
        <br />
        <?php voting::showVote($itemId2, $userId1); ?>
        <br />
        <?php voting::showVote($itemId3, $userId1); ?>
        <br />
        <?php voting::showVote($itemId4, $userId1); ?>
        <br />
    </body>
</html>

 

voting/voting.php
In this script you need to add your database-settings on line 046

<?php

class voting {

    public function showVote($itemId, $userId) {     
        $db = voting::dbConn();
        $votesCount = voting::dbCountVotes($db, $itemId);
        ?>
            <script>
            function doVote(value, itemId) {
                $.ajax({
                    type: "POST",
                    url: "voting/voting.php",
                    data: { 
                        itemId: itemId, 
                        userId: "<?php echo $userId; ?>", 
                        vote: value 
                    }
                }).done(function( msg ) {
                    document.getElementById("result"+itemId).innerHTML = msg;
                });
            }
            </script>
            <a title="+1" href="#" onclick="doVote('1', '<? echo $itemId; ?>');return false;" style="text-decoration: none"><img width="15px" src="voting/images/plus.png"/></a>
            <b id="result<?php echo $itemId; ?>"><?php echo $votesCount; ?></b>
            <a title="-1" href="#" onclick="doVote('-1', '<? echo $itemId; ?>');return false;" style="text-decoration: none"><img width="15px" src="voting/images/minus.png"/></a>
        <?php
    }

    public function registerVote() {
        // Make db connection
        $db = voting::dbConn();
        // Check if user vated already
        $alreadyVoted = voting::alreadyVoted($db,$_POST['itemId'],$_POST['userId']);
        // Update vote if already voted else add a new vote
        if($alreadyVoted == 1) {
            voting::updateVote($db,$_POST['itemId'],$_POST['userId'],$_POST['vote']);
        }else{
            voting::addVote($db,$_POST['itemId'],$_POST['userId'],$_POST['vote']);
        }
        // Finally return the new votes count.
        echo voting::dbCountVotes($db, $_POST['itemId']);
    }

    private function dbConn() {
        $db = new PDO('mysql:host=localhost;dbname=YourDatabaseNamew;charset=utf8', 'YourDatabaseUser', 'YourDatabaseUserPassword');
        //  Put PDO into exception mode
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //
        // Turn off prepare emulation which is enabled in MySQL driver by default. It should be turned off to use PDO safely and is only usable if you are using an old version of MySQL.
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        return $db;
    }

    private function dbCountVotes($db,$itemId) {
        try {
            $sth = $db->prepare('SELECT sum(`vote`) AS count FROM `voting` WHERE `itemId` = :itemId');
            $sth->bindParam(':itemId', $itemId);
            $sth->execute();
            $result = $sth->fetchColumn();
            if(empty($result)) { $result = 0; }
            return $result;
        }
        catch(PDOException $ex) {
            echo '<a title="'.$ex->getMessage().'">An Error occured!</a>'; //user friendly message
            die();
        }
    }

    private function alreadyVoted($db,$itemId,$userId) {
        //returns true or false
        try {
            $sth = $db->prepare('SELECT count(id) AS count FROM `voting` WHERE `itemId` = :itemId AND userId = :userId');
            $sth->bindParam(':itemId', $itemId);
            $sth->bindParam(':userId', $userId);
            $sth->execute();
            $result = $sth->fetch();
            return $result['count'];
        }
        catch(PDOException $ex) {
            echo '<a title="'.$ex->getMessage().'">An Error occured!</a>'; //user friendly message
            die();
        }
    }

    private function addVote($db,$itemId,$userId,$vote) {
        //returns true or false
        try {
            $sth = $db->prepare('INSERT INTO `voting` ( `itemId`, `userId`, `vote` ) VALUES ( :itemId, :userId, :vote )');
            $sth->bindParam(':itemId', $itemId);
            $sth->bindParam(':userId', $userId);
            $sth->bindParam(':vote', $vote);
            $sth->execute();
            return 0;
        }
        catch(PDOException $ex) {
            echo '<a title="'.$ex->getMessage().'">An Error occured!</a>'; //user friendly message
            die();
        }
    }

    private function updateVote($db,$itemId,$userId,$vote) {
        //returns true or false
        try {
            $sth = $db->prepare('UPDATE `voting` SET `vote` = :vote WHERE `itemId` = :itemId AND `userId` = :userId');
            $sth->bindParam(':itemId', $itemId);
            $sth->bindParam(':userId', $userId);
            $sth->bindParam(':vote', $vote);
            $sth->execute();
            return 0;
        }
        catch(PDOException $ex) {
            echo '<a title="'.$ex->getMessage().'">An Error occured!</a>'; //user friendly message
            die();
        }
    }

}

if($_POST['itemId'] && $_POST['userId']) { voting::registerVote(); }
?>

 

The database table that you have to add:

CREATE TABLE IF NOT EXISTS `voting` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemId` int(9) NOT NULL,
  `userId` int(9) NOT NULL,
  `vote` tinyint(1) NOT NULL,
  PRIMARY KEY (`id`)
);

[ Download ]