One of the simplest and most popular add-ons to a Web site is anonline poll, allowing visitors to vote on hot-button issues. In thisarticle, find out how PHP can be used to build a powerful, good-lookingonline poll for your Web site, and also learn a little bit about its imageand cookie manipulation functions.
With the database taken care of, it's time to put together the Web pages that the user sees. The first of these is "start.php", which connects to the database to get the latest poll, and displays it with a list of possible responses.
// start.php - displays poll and responses
// connect to database and query
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to
$query = "SELECT id, question, response1, response2, response3 from $table
ORDER BY id DESC LIMIT 0,1";
$result = mysql_db_query($database, $query, $connection) or die ("Could not
execute query: $query. " . mysql_error());
// if questions are available, display vote form
if (mysql_num_rows($result) > 0)
list ($id, $question, $response1, $response2, $response3) =
<form method="post" action="vote.php">
<b><? echo $question; ?></b>
<input type="Radio" name="response" value="1"><? echo $response1; ?>
<input type="Radio" name="response" value="2"><? echo $response2; ?>
<input type="Radio" name="response" value="3"><? echo $response3; ?>
<input type="hidden" name="id" value="<? echo $id; ?>">
<!-- explanation coming up - keep reading -->
<font size=-2><a href="archive.php?id=<? echo $id; ?>">view
<font size=-2><a href="archive.php">view past polls</a></font>
<input type=submit name=submit value="Vote">
// or display a status message
<i>No polls available!</i>
// close connection
Pay special attention to the SQL query I'm running - I'm
using the ORDER BY, DESC and LIMIT keywords to ensure that I get the latest record (read: question) from the database. Once the query returns a result, the list() function is used to walk through the result set and assign each field to a variable; these are then displayed in a form. The identifier for the poll question is also included in the form, as a hidden field; when the form is submitted, this identifier will be used to ensure that the correct record is updated.
If the database is empty, an error message is displayed. In this case, I've already inserted one question into the database, so you won't see it at all; however, it's good programming practice to ensure that all eventualities are accounted for, even the ones that don't occur that often.
In case you're wondering about the files include()d at the top of the script - they simply contain variables and functions common to the application. Here's what "config.php" looks like:
// config.php - global variables for all database operations
Here's what it looks like:
This article copyright Melonfire 2001. All rights reserved.