Learning PHP and MySQL
Example 10-10 Combining form processing and database querying
?php
function query_db($qstring) {
include('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));
}
$query = "SELECT * FROM `books` NATURAL JOIN `authors`
WHERE `books`.`title` like '%$qstring%'";
$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>Author</th><th>Pages</th></tr>";
while ($result_row = $result->fetchRow()) {
echo "<tr><td>";
echo $result_row[1] . '</td><td>';
echo $result_row[4] . '</td><td>';
echo $result_row[2] . '</td></tr>';
}
echo ("</table>");
$connection->disconnect();
}
?>
<html>
<head>
<title>Building a Form</title>
</head>
<body>
<?php
$search = $_GET["search"];
$self = $_SERVER['PHP_SELF'];
if ($search != NULL){
echo "The search string is: <strong>$search</strong>.";
query_db($search);
}
else {
echo ('
<form action="'.$self.'" method="get">
<label>Search:
<input type="text" name="search" id="search" />
</label>
<input type="submit" value="Go!" />
</form>
');
}
?>
</body>
</html>
Posted by on 08/18 at 11:46 AM
Next entry: Example 10-11 The index.php file to create
Previous entry: Example 10-09 Converting between time zones based on user input