O'Reilly logo

Learning PHP and MySQL by Jon A. Phillips, Michele E. Davis

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Presenting a Form to Add and Process in One File

We're building a form that allows a web user to add a title to the books table. Example 12-6 is a slightly longer example, because we display and process the form in one file, but it should look familiar to you since we're simply combining several steps that we've done separately before.

Example 12-6. Using input from a form to add a title

<?php
// Define a function to perform the database insert and display the titles
function insert_db($title, $pages){
require_once('db_login.php');
require_once('DB.php');
$connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database");
if (DB::isError($connection)){
die ("Could not connect to the database: <br />". DB::errorMessage($connection));
}
// The query includes the form sumbission values that were passed to the function
$query = "INSERT INTO `books` VALUES (NULL,'$title','$pages')";
$result = $connection->query($query);
if (DB::isError($result)){
die("Could not query the database: <br />". $query." ".DB::errorMessage($result));
}
echo "Inserted OK.<br />"; // Display the table $query = "SELECT * FROM `books`"; $result = $connection->query($query); if (DB::isError($result)){ die("Could not query the database: <br />". $query." ".DB::errorMessage($result)); } echo '<table border="1">'; echo "<tr><th>Title</th><th>Pages</th></tr>"; while ($result_row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { echo "<tr><td>"; echo $result_row["title"] . '</td><td>'; echo $result_row["pages"] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required