How to Code a Simple PHP Voting System PHP/MySQL tutorial

Background
A few years ago, I wanted to code a very simple PHP voting system. I never quite got around to doing it so I resolved to work on that today. This tutorial is the result of that effort. 🙂

Getting Started
One of the first things I determine when I’m planning a php script is whether it will require the use of a MySQL database. In the case of this script, it will. So, we need to set about creating the schema to create the table that will run the script. You’ll find that immediately below:

CREATE TABLE items (
itemid MEDIUMINT(30) NOT NULL AUTO_INCREMENT,
itemtext TEXT,
pos TINYINT(3),
PRIMARY KEY (itemid)
);

Next, let’s populate the table with a few items to play around with.

INSERT INTO items (itemtext,pos) VALUES ('Subnautica','1');
INSERT INTO items (itemtext,pos) VALUES ('Terraria','2');
INSERT INTO items (itemtext,pos) VALUES ('Sims 3','3');
INSERT INTO items (itemtext,pos) VALUES ('Secret World','4');

The whole script consists of 3 php files:
– the config file (with the database connection code)
– the simplevote file (which shows the list of items)
– the vote file (which processes any upvoting or downvoting you do)

I also made a couple of + and – png files to stand in for the upvote and downvote links. You can download the zip file containing everything by clicking here:

I also re-wrote the script with PDO (which makes it much more secure) which you can download by clicking here:

To see the demo, click here.

As for the code (of the original, non-pdo version of the script), you’ll find each page embedded below.

config.php

<?php

   // Database Settings -- Edit these settings
   $hostname = "localhost";  // should work in most cases
   $dbuser = "your_dbuser";  // username for your database
   $dbpass = "your_dbpass";        // the password for your database
   $db = "your_dbname";  // the database name

   // Connect to the database -- Do not edit
   $dbconn = mysql_connect($hostname, $dbuser, $dbpass) or die (mysql_error("Please correct your db settings and try again."));
   $tableconn = mysql_select_db($db) or die (mysql_error("Unable to connect to database. Have you created it yet?"));
?>

simplevote.php

<?php

// A Simple PHP Voting Script
// Coded by Kim Enders 1/9/18

include ("config.php");

// Now for the real meat of the script
?>

<!-- Let's add some html to structure the style of the voting system -->
<!DOCTYPE html>
<html>
<head>
<title>A simple voting system</title>
<!-- An internal css stylesheet - can always be changed to external css if desired -->
<style>

p {
    font-size: 18px;
    font-family: "Times New Roman", Times, serif;
}

table {
  border:1px solid black;
  width:200px;
  text-align: left;
  padding: 10px;
  margin-left:auto; 
  margin-right:auto;
  
}

</style>
</head>
<body>

<!-- I'm going to include the voting system in a table so starting that now with an outer table with a border-->
<table>

<?php

// Let's first count all of the records for a later snippet of code that disallows the top item to be upvoteable (the pos # of the top item is the same number as the total amount of records)
$countrecords = "SELECT COUNT(itemid) AS totalrecords FROM items WHERE itemid >= '1'";
$result = mysql_query($countrecords);

if($result) {
$row = mysql_fetch_array ($result,MYSQL_ASSOC);

// assign the number of records to a variable so we can use it to compare with later
$numrecords = '' . $row['totalrecords'] . '';

      // now, grab all of the items we're working with
      $items = "SELECT * FROM items WHERE itemid >= '1' ORDER BY pos DESC";
      $result = mysql_query($items);
      
            while ($row=mysql_fetch_array ($result,MYSQL_ASSOC)) {
            // assign variables to each bit of data that we'll be working with
            $itemtext = '' . $row['itemtext'] . '';
            $pos = '' . $row['pos'] . '';
            $id = '' . $row['itemid'] . '';

            // now start to output them, row by row
            echo "<tr><td><p>$itemtext</p></td>";

            echo "<td><p>";

           // disallow upvoting if the item is the top pos
           if($pos != $numrecords) {
           echo "<a href=\"vote.php?action=upvote&pos=$pos&id=$id\"><img src=\"plus.png\" /></a>";
           }

            echo "</p></td>";

            echo "<td><p>";

           //disallow downvoting if the item pos is 1 (the lowest number we want to use)
           if($pos!= '1') { 

           echo "<a href=\"vote.php?action=downvote&pos=$pos&id=$id\"><img src=\"minus.png\" /></a>";

           }

                       echo "</p></td></tr>";

         }

}
   
?>

<!-- now close the table -->
</tr></table>

</body>
</html>

And that’s it. It’s a very rudimentary system but it does work. It can be expanded upon and developed further, likely fairly easily. It would also likely be preferable to dress it up more nicely in CSS or better yet, simply break down and use jquery instead which seems to often make a much smoother, attractive system. Either way, hope this helped!

If you found this post useful, leave a comment below!

Leave a Reply

Your email address will not be published. Required fields are marked *