Democracy, The PHP Way - Start Me Up (
Page 4 of 9 )
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.
<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="white">
<?
// start.php - displays poll and responses
// includes
include("config.php");
include("common.php");
// connect to database and query
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to
connect!");
$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) =
mysql_fetch_row($result);
?>
<form method="post" action="vote.php">
<b><? echo $question; ?></b>
<p>
<input type="Radio" name="response" value="1"><? echo $response1; ?>
<p>
<input type="Radio" name="response" value="2"><? echo $response2; ?>
<p>
<input type="Radio" name="response" value="3"><? echo $response3; ?>
<input type="hidden" name="id" value="<? echo $id; ?>">
<p>
<!-- explanation coming up - keep reading -->
<font size=-2><a href="archive.php?id=<? echo $id; ?>">view
results</a></font>
<font size=-2><a href="archive.php">view past polls</a></font>
<p>
<input type=submit name=submit value="Vote">
</form>
<?
}
// or display a status message
else
{
?>
<i>No polls available!</i>
<?
}
// close connection
mysql_close($connection);
?>
</body>
</html>
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
$hostname="somehost";
$user="us54738";
$pass="7834535";
$database="db54738";
$table="poll";
?>
Here's what it looks like:
This article
copyright Melonfire 2001. All rights
reserved.