- 2. Create a PHP script named search.php to submit a request to Apache Derby:
<?php
// include the menu_lib.php file within this script
require('menu_lib.php');
function menu_footer() {
print '</body></html>';
}
// display the search form
readfile('search.html');
// assign the user-supplied input to a local variable
if (!isset($_POST['search'])) {
print "Please supply a search string.";
print menu_footer();
exit;
}
// you can filter the input here
$search = preg_match('#^[^\W_]+$#', $_POST['search']);
if (!$search) {
print "Your search string may only contain letters and numbers.";
print menu_footer();
exit;
}
$search = $_POST['search'];
// Create the connection, catching any exceptions
try {
// connect with default parameter values
$conn = menu_connect();
}
catch (PDOException $e) {
print "Failed to connect: " . $e->getMessage();
exit;
}
// Use a parameter marker to support variable input
$sql = 'SELECT name, description
FROM menu.food
WHERE name LIKE ?';
// Prepare the statement
$stmt = $conn->prepare($sql);
// Execute the statement, passing in an array of input variables
$stmt->execute(array($search));
while ($row = $stmt->fetch()) {
// Retrieve column by index number
print "<p>Name: {$row[0]}\n";
// Retrieve column by column name
print "Description: {$row['DESCRIPTION']}</p>\n";
}
$stmt = null;
$conn = null;
print menu_footer();
?>
If you have time, complete the additional exercises for search.php to gain hands-on experience with Apache Derby's support for standard SQL comparison functions.