Setting Up Database Driven Websites - Making a PHP Script (Page 7 of 8 )
We've created the database, now let's make the PHP scripts that form the guts of our web database example.
Creating the PHP Scripts To keep things really simple, we will just create two scripts: one that lists all the entries in the database, and one that allows us to add new entries.
index.php3 Create a new directory called example in your web directory:
# cd /home/httpd/htdocs
# mkdir example
Next, create a file called index.php3 in this directory. It should contain:
<html>
<head><title>Web Database Sample Index</title>
</head>
<body bgcolor=#ffffff>
<h1>Data from mytable</h1>
<?
mysql_connect("localhost", "webuser", "");
$query = "SELECT name, phone FROM mytable";
$result = mysql_db_query("example", $query);
if ($result) {
echo "Found these entries in the database:<ul>";
while ($r = mysql_fetch_array($result)) {
$name = $r["name"];
$phone = $r["phone"];
echo "<li>$name, $phone";
}
echo "</ul>";
} else {
echo "No data.";
}
mysql_free_result($result);
?>
<p><a href="add.php3">Add new entry</a>
</body>
</html>
add.php3
Next, we create add.php3 in the same directory. This script does two things, first it will prompt the user for information to add to the database. Second, it will add this information to the database. This second function is normally put in a separate file, but it is so easy to do that we cram them both into one PHP script:
<html>
<head><title>Web Database Sample Inserting</title>
</head>
<body bgcolor=#ffffff>
<?
if (isset($name) && isset($phone)) {
mysql_connect("localhost", "webuser", "");
$query = "INSERT INTO mytable VALUES ('$name', '$phone')";
$result = mysql_db_query("example", $query);
if ($result) {
echo "<p>$name was added to the database</p>";
}
}
?>
<h1>Add an entry</h1>
<form>
Name: <input type=text name='name'><br>
Phone: <input type=text name='phone'><br>
<input type=submit>
</form>
<p><a href="index.php3">Back to index</a>
</body>
</html>
That's it, nice and simple. Now let's test it.
Next: Testing the Script >>
More Administration Articles
More By Ying Zhang