Democracy, The PHP Way - Adding More... (
Page 9 of 9 )
The final
item on today's menu is perhaps the simplest - a form which allows
administrators to easily add new questions to the system.
This script,
named "add.php", is divided into two sections. The initial section is the form
itself, with fields for the question and possible responses.
<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="white">
<?
// this script is meant only for the administrator - add new polls to the
database
// $submit does not exist -> forms has not been submitted -> display
initial page
if (!$submit)
{
?>
<table border="0" cellspacing="5" cellpadding="5">
<form action="add.php" method="post">
<tr>
<td>Poll question<br><input type="Text" name="question" size="25"></td>
</tr>
<tr>
<td>Response 1<br><input type="Text" name="response1" size="25"></td>
</tr>
<tr>
<td>Response 2<br><input type="Text" name="response2" size="25"></td>
</tr>
<tr>
<td>Response 3<br><input type="Text" name="response3" size="25"></td>
</tr>
<tr>
<td align=center><input type=submit name=submit value="Add Question"></td>
</tr>
</form>
</table>
<?
}
// form has been submitted - process data
else
{
// form processing code goes here
}
?>
</body>
</html>
Once the form has been submitted, the data from the form
fields is assimilated into an SQL query and INSERTed into the database.
<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="white">
<?
// this script is meant only for the administrator - add new polls to the
database
// $submit does not exist -> forms has not been submitted -> display
initial page
if (!$submit)
{
// initial form goes here
}
// form has been submitted - process data
else
{
// includes
include("config.php");
include("common.php");
// connect and insert form data into database
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to
connect!");
$query = "INSERT INTO $table (question, response1, response2, response3,
date) VALUES ('$question', '$response1', '$response2', '$response3',
NOW())";
$result = mysql_db_query($database, $query, $connection) or die ("Could not
execute query: $query. " . mysql_error());
// check for result code
if ($result)
{
echo "<i>Entry successfully added. Click here to <a
href=start.php>view</a></i>";
}
else
{
echo "<i>Error! Please <a href=add.php>try again</a></i>";
}
// close connection
mysql_close($connection);
}
?>
</body>
</html>
And here's what it looks like:

And that's about it. Hopefully, this exercise gave you
some insight into how PHP can be used to build a simple Web application, and
illustrated its power and flexibility as a rapid development tool for the Web
medium. You can use the example scripts above to build your own simple poll, or
even modify them a little bit and create an online quiz (it *is* the same basic
principle - one question, three answers). Either way, have fun...and stay
healthy!
This
article copyright Melonfire 2001. All
rights reserved.