Going to the Polls with PHP: Part 2 - Admin panel
The next step in building this application is to provide the administrator with an easy way to add and delete questions and answers from the MySQL database. Consider the script admin.php, which provides the starting point for these tasks:
As you can see, there are two sections in this script. The first half connects to the database and prints a list of all available questions, with “view report” and “delete” links next to each (more on this these shortly). The second half contains a simple form for the administrator to add a new question and up to five possible answers.
Once the form is submitted, the data entered by the administrator gets POST-ed to the script add.php, which validates it and saves it to the database. Here’s the code:
This script has a lot of things happening in it, so let’s go through it step-by-step.
The first order of business is to sanitize the data entered by the user. There are a bunch of lines of code at the top of the script that do this, by checking for a question title and verifying that at least two answer choices are present. Notice my use of the trim() function to weed out any input that contains only empty spaces, and the sizeof() function that verifies the presence of at least two valid answer choices in the $POST['options'] array. Any failure here results in an error message, and the script will refuse to proceed further.
Assuming all the data is acceptable, the next step is to save it to the database. First, the question is saved to the questions table via an INSERT query. The ID generated by this INSERT query is retrieved via the mysql_insert_id() function, and used to link the answer choices to the question when saving them to the answers table. Since there will be more than one answer choice for each question, a foreach() loop is used to repeatedly run an INSERT query - once for each possible answer choice (with MySQL 4.1 and the PHP 5 mysqli extension, you could instead use a prepared query here - feel free to experiment with this alternative yourself).
That takes care of adding questions and answers. Now, what about removing them?
Well, go back and take a look at the admin.php script. You’ll see that, next to each question displayed, there is a “delete” link, which points to the script delete.php. You’ll also see that this script is passed an input parameter, the question ID, on the URL itself. It’s clear, then, that delete.php can use this input parameter to identify the corresponding question in the questions table (as well as its answers - the question ID is common to both tables, remember) and run a DELETE query to erase this data from the system.
Here’s the code that actually does the work:
As you can see, the question ID passed through the GET method is retrieved by the script, and used inside two DELETE queries to remove all the records linked to that ID.
Playing the Numbers
Now for possibly the most interesting section of this tutorial: Item #3. Obviously, once you have users and votes coming in, you’d like to see reports of how the votes are distributed. This involves connecting to the database, using the question ID to extract the correct record set, calculating the total number of votes and the percentage each option has of the total, and displaying this information in a table.
Here’s what all that looks like in PHP:
This script, view.php, is activated from admin.php in much the same way as delete.php - a question ID is passed to it as an input parameter, and that ID is used to retrieve the corresponding answers and the votes each one has gathered. Once the answer set has been retrieved, the total number of votes submitted can be calculated, and the percentage share of each option in the total vote can be obtained. This data is then displayed in a simple HTML table.
You need to be careful when converting the absolute numbers into percentages - if there aren’t any votes yet, you can get some pretty strange division by zero errors. To avoid this, the second query in the script uses MySQL’s SUM() function and GROUP BY clause to obtain the total number of votes for a particular question. If this total is 0, no votes have yet been cast, and a message to that effect is displayed; if the total is greater than 0, the individual percentages are calculated.
Exit Poll
The way things are currently set up, a single user can vote for a particular option more than once, thereby contravening one of the basic principles of democracy: one citizen, one vote. Although it’s unlikely that many users would have the patience or inclination to do this; however, it is a hole, and should be plugged.
I’ve decided to set a cookie on the voter’s system once the vote has successfully been cast. With the addition of a few lines of script, I can now check for the presence or absence of this cookie whenever a user tries to vote, and thereby decide whether or not to accept the vote.
Here’s the code, which gets added to the very top of user_submit.php:
With this in place, when a user votes, a cookie is set on the client browser, containing the ID for the question the user voted on. At each subsequent vote attempt, the script will first check for the presence of the cookie and, if it exists, the value of the cookie variable $_COOKIE['lastpoll']. Only if the cookie is absent (indicating that this is a first-time voter) or the value of $_COOKIE['lastpoll'] is different from the ID of the current poll question (indicating that the user has voted previously, but in response to a different question), will the vote be accepted.
This is by no means foolproof: any reasonably adept user can delete the cookie from the client’s cache and vote again - but it does add a layer of security to the process. The ideal method, of course, would be to track voters on the server itself and deny votes to those who have already voted; and indeed, this is a feasible alternative if the site requires users to register with unique usernames before accessing its online polls.
Copyright Melonfire, 2005 (http://www.melonfire.com). All rights reserved.

- Going to the Polls with PHP: Part 1 - The frontside
- Creating an object oriented MySQL abstraction class
- Showing the top domain referrals to your site
- Get Google Adsense statistics by using PHP
- Creating sortable lists with PHP and Ajax
- Using PHP to get prices from Amazon.com
- AJAX Generic Form Parser - With Validation
- Cache in PHP
- PHP script to display Google PageRank
- Determining Whether an Email Account Exists
- Underwater room photo effect
- Dynamic Recessed Watercolor Typography in Photoshop
- Login Control in Visual Studio 2005
- Parkling Hot Girl In Photoshop
- Fiery Photoshop Space Explosion Tutorial
- Urban landscape
- Advanced Glow Effects
- The Scream Photo Effects
- Advanced Sharpening in Photoshop
- How to Illustrate a Wooden Frame on a Wall Scene
Login
Friends' Sites
Contact Us
Categories
- 3D
- ASP
- C#
- CSS
- Database
- Flash
- GIMP
- Hosting
- Illustrator
- Java
- Javascript
- Linux
- Photoshop
- PHP
- Web Design
- Windows

2,836 views
No comments

No comments
Jump to comment form | comments rss [?] | trackback uri [?]