Created
January 29, 2025 06:20
-
-
Save Mwamitovi/853c5a82e641019ad4de85ebbaf87dc5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Chapter-8: Exercises | |
// The following exercises use a database table called dishes with the following structure: | |
// -- CREATE TABLE dishes ( | |
// -- dish_id INT, | |
// -- dish_name VARCHAR(255), | |
// -- price DECIMAL(4,2), | |
// -- is_spicy INT | |
// -- ) | |
// Here is some sample data to put into the dishes table: | |
// -- INSERT INTO dishes VALUES (1,'Walnut Bun',1.00,0) | |
// -- INSERT INTO dishes VALUES (2,'Cashew Nuts and White Mushrooms',4.95,0) | |
// -- INSERT INTO dishes VALUES (3,'Dried Mulberries',3.00,0) | |
// -- INSERT INTO dishes VALUES (4,'Eggplant with Chili Sauce',6.50,1) | |
// -- INSERT INTO dishes VALUES (5,'Red Bean Bun',1.00,0) | |
// -- INSERT INTO dishes VALUES (6,'General Tso''s Chicken',5.50,1) | |
// Question-1 | |
// 1. Write a program that lists all of the dishes in the table, sorted by price. | |
// Answer-1 | |
try { | |
// Connect | |
$db = new PDO('sqlite:/tmp/restaurant.db'); | |
// Set up exceptions on DB errors | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$stmt = $db->query('SELECT * FROM dishes ORDER BY price'); | |
$dishes = $stmt->fetchAll(); | |
if (count($dishes) == 0) { | |
$html = '<p>No dishes to display</p>'; | |
} else { | |
$html = "<table>\n"; | |
$html .= "<tr><th>Dish Name</th><th>Price</th><th>Spicy?</th></tr>\n"; | |
foreach ($dishes as $dish) { | |
$html .= '<tr><td>' . | |
htmlentities($dish['dish_name']) . '</td><td>$' . | |
sprintf('%.02f', $dish['price']) . '</td><td>' . | |
($dish['is_spicy'] ? 'Yes' : 'No') . "</td></tr>\n"; | |
} | |
$html .= "</table>"; | |
} | |
} catch (PDOException $e) { | |
$html = "Can't show dishes: " . $e->getMessage(); | |
} | |
print $html; | |
// Question-2 | |
// 2. Write a program that displays a form asking for a price. When the form is submitted, | |
// the program should print out the names and prices of the dishes whose price is at least the submitted price. | |
// Don’t retrieve from the database any rows or columns that aren’t printed in the table. | |
// Answer-2 | |
// Load the form helper class | |
require 'FormHelper.php'; | |
// Connect to the database | |
try { | |
$db = new PDO('sqlite:/tmp/restaurant.db'); | |
} catch (PDOException $e) { | |
print "Can't connect: " . $e->getMessage(); | |
exit(); | |
} | |
// Set up exceptions on DB errors | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
// Set up fetch mode: rows as objects | |
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); | |
// The main page logic: | |
// - If the form is submitted, validate and then process or redisplay | |
// - If it's not submitted, display | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// If validate_form() returns errors, pass them to show_form() | |
list($errors, $input) = validate_form(); | |
if ($errors) { | |
show_form($errors); | |
} else { | |
// The submitted data is valid, so process it | |
process_form($input); | |
} | |
} else { | |
// The form wasn't submitted, so display | |
show_form(); | |
} | |
function show_form($errors = array()) | |
{ | |
// Set up the $form object with proper defaults | |
$form = new FormHelper(); | |
// All the HTML and form display is in a separate file for clarity | |
include 'price-form.php'; | |
} | |
function validate_form() | |
{ | |
$input = array(); | |
$errors = array(); | |
// Minimum price must be a valid floating-point number | |
$input['min_price'] = filter_input( | |
INPUT_POST, | |
'min_price', | |
FILTER_VALIDATE_FLOAT | |
); | |
if ($input['min_price'] === null || $input['min_price'] === false) { | |
$errors[] = 'Please enter a valid minimum price.'; | |
} | |
return array($errors, $input); | |
} | |
function process_form($input) | |
{ | |
// Access the global variable $db inside this function | |
global $db; | |
// Build up the query | |
$sql = 'SELECT dish_name, price, is_spicy FROM dishes WHERE | |
price >= ?'; | |
// Send the query to the database program and get all the rows back | |
$stmt = $db->prepare($sql); | |
$stmt->execute(array($input['min_price'])); | |
$dishes = $stmt->fetchAll(); | |
if (count($dishes) == 0) { | |
print 'No dishes matched.'; | |
} else { | |
print '<table>'; | |
print '<tr><th>Dish Name</th><th>Price</th><th>Spicy?</th></tr>'; | |
foreach ($dishes as $dish) { | |
if ($dish->is_spicy == 1) { | |
$spicy = 'Yes'; | |
} else { | |
$spicy = 'No'; | |
} | |
} | |
printf( | |
'<tr><td>%s</td><td>$%.02f</td><td>%s</td></tr>', | |
htmlentities($dish->dish_name), | |
$dish->price, | |
$spicy | |
); | |
print '</table>'; | |
} | |
} | |
// The code relies on the FormHelper.php file discussed in Chapter 7. | |
// The price-form.php file referenced, which displays the form HTML, contains: ?> | |
<form method="POST" action="<?= $form->encode($_SERVER['PHP_SELF']) ?>"> | |
<table> | |
<?php if ($errors) { ?> | |
<tr> | |
<td>You need to correct the following errors:</td> | |
<td> | |
<ul> | |
<?php foreach ($errors as $error) { ?> | |
<li><?= $form->encode($error) ?></li> | |
<?php } ?> | |
</ul> | |
</td> | |
<?php } ?> | |
<tr> | |
<td>Minimum Price:</td> | |
<td><?= $form->input('text', ['name' => 'min_price']) ?></td> | |
</tr> | |
<tr> | |
<td colspan="2" align="center"> | |
<?= $form->input('submit', [ | |
'name' => 'search', | |
'value' => 'Search' | |
]) ?> | |
</td> | |
</tr> | |
</table> | |
</form><?php | |
// Question-3 | |
// 3. Write a program that displays a form with a <select> menu of dish names. | |
// Create the dish names to display by retrieving them from the database. | |
// When the form is submitted, the program should print out all of the information in the table (ID, name, price, and spiciness) for the selected dish. | |
// Answer-3 | |
// Load the form helper class | |
require 'FormHelper.php'; | |
// Connect to the database | |
try { | |
$db = new PDO('sqlite:/tmp/restaurant.db'); | |
} catch (PDOException $e) { | |
print "Can't connect: " . $e->getMessage(); | |
exit(); | |
} | |
// Set up exceptions on DB errors | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
// Set up fetch mode: rows as objects | |
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); | |
// The main page logic: | |
// - If the form is submitted, validate and then process or redisplay | |
// - If it's not submitted, display | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// If validate_form() returns errors, pass them to show_form() | |
list($errors, $input) = validate_form(); | |
if ($errors) { | |
show_form($errors); | |
} else { | |
// The submitted data is valid, so process it | |
process_form($input); | |
} | |
} else { | |
// The form wasn't submitted, so display | |
show_form(); | |
} | |
function show_form2($errors = array()) | |
{ | |
global $db; | |
// Set up the $form object with proper defaults | |
$form = new FormHelper(); | |
// Retrieve the list of dish names to use from the database | |
$sql = 'SELECT dish_id, dish_name FROM dishes ORDER BY dish_name'; | |
$stmt = $db->query($sql); | |
$dishes = array(); | |
while ($row = $stmt->fetch()) { | |
$dishes[$row->dish_id] = $row->dish_name; | |
} | |
// All the HTML and form display is in a separate file for clarity | |
include 'dish-form.php'; | |
} | |
function validate_form2() | |
{ | |
$input = array(); | |
$errors = array(); | |
// As long as some dish_id value is submitted, we'll consider it OK. | |
// If it doesn't match any dishes in the database, process_form() | |
// can report that. | |
if (isset($_POST['dish_id'])) { | |
$input['dish_id'] = $_POST['dish_id']; | |
} else { | |
$errors[] = 'Please select a dish.'; | |
} | |
return array($errors, $input); | |
} | |
function process_form2($input) | |
{ | |
// Access the global variable $db inside this function | |
global $db; | |
// Build up the query | |
$sql = 'SELECT dish_id, dish_name, price, is_spicy FROM dishes WHERE | |
dish_id = ?'; | |
// Send the query to the database program and get all the rows back | |
$stmt = $db->prepare($sql); | |
$stmt->execute(array($input['dish_id'])); | |
$dish = $stmt->fetch(); | |
if (count($dish) == 0) { | |
print 'No dishes matched.'; | |
} else { | |
print '<table>'; | |
print '<tr><th>ID</th><th>Dish Name</th><th>Price</th>'; | |
print '<th>Spicy?</th></tr>'; | |
if ($dish->is_spicy == 1) { | |
$spicy = 'Yes'; | |
} else { | |
$spicy = 'No'; | |
} | |
printf( | |
'<tr><td>%d</td><td>%s</td><td>$%.02f</td><td>%s</td></tr>', | |
$dish->dish_id, | |
htmlentities($dish->dish_name), | |
$dish->price, | |
$spicy | |
); | |
print '</table>'; | |
} | |
} | |
// The code relies on the FormHelper.php file discussed in Chapter 7. | |
// The dish-form.php file referenced, which displays the form HTML, contains: ?> | |
<form method="POST" action="<?= $form->encode($_SERVER['PHP_SELF']) ?>"> | |
<table> | |
<?php if ($errors) { ?> | |
<tr> | |
<td>You need to correct the following errors:</td> | |
<td> | |
<ul> | |
<?php foreach ($errors as $error) { ?> | |
<li><?= $form->encode($error) ?></li> | |
<?php } ?> | |
</ul> | |
</td> | |
<?php } ?> | |
<tr> | |
<td>Dish:</td> | |
<td><?= $form->select($dishes, ['name' => 'dish_id']) ?></td> | |
</tr> | |
<tr> | |
<td colspan="2" align="center"> | |
<?= $form->input('submit', [ | |
'name' => 'info', | |
'value' => 'Get Dish Info' | |
]) ?> | |
</td> | |
</tr> | |
</table> | |
<?php | |
// Question-4 | |
// 4. Create a new table that holds information about restaurant customers. | |
// The table should store the following information about each customer: customer ID, name, phone number, | |
// and the ID of the customer’s favorite dish. Write a program that displays a form for putting a new customer into the table. | |
// The part of the form for entering the customer’s favorite dish should be a <select> menu of dish names. | |
// The customer’s ID should be generated by your program, not entered in the form. | |
// Answer-4 | |
// Load the form helper class | |
require 'FormHelper.php'; | |
// Connect to the database | |
try { | |
$db = new PDO('sqlite:/tmp/restaurant.db'); | |
} catch (PDOException $e) { | |
print "Can't connect: " . $e->getMessage(); | |
exit(); | |
} | |
// Set up exceptions on DB errors | |
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
// Set up fetch mode: rows as objects | |
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); | |
// Put the list of dish IDs and names in a global array because | |
// we'll need it in show_form() and validate_form() | |
$dishes = array(); | |
$sql = 'SELECT dish_id, dish_name FROM dishes ORDER BY dish_name'; | |
$stmt = $db->query($sql); | |
while ($row = $stmt->fetch()) { | |
$dishes[$row->dish_id] = $row->dish_name; | |
} | |
// The main page logic: | |
// - If the form is submitted, validate and then process or redisplay | |
// - If it's not submitted, display | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
// If validate_form() returns errors, pass them to show_form() | |
list($errors, $input) = validate_form(); | |
if ($errors) { | |
show_form($errors); | |
} else { | |
// The submitted data is valid, so process it | |
process_form($input); | |
} | |
} else { | |
// The form wasn't submitted, so display | |
show_form(); | |
} | |
function show_form3($errors = array()) | |
{ | |
global $db, $dishes; | |
// Set up the $form object with proper defaults | |
$form = new FormHelper(); | |
// All the HTML and form display is in a separate file for clarity | |
include 'customer-form.php'; | |
} | |
function validate_form3() | |
{ | |
global $dishes; | |
$input = array(); | |
$errors = array(); | |
// Make sure a dish_id valid is submitted and in $dishes. | |
// As long as some dish_id value is submitted, we'll consider it OK. | |
// If it doesn't match any dishes in the database, process_form() | |
// can report that. | |
$input['dish_id'] = $_POST['dish_id'] ?? ''; | |
if (!array_key_exists($input['dish_id'], $dishes)) { | |
$errors[] = 'Please select a valid dish.'; | |
} | |
// Name is required | |
$input['name'] = trim($_POST['name'] ?? ''); | |
if (0 == strlen($input['name'])) { | |
$errors[] = 'Please enter a name.'; | |
} | |
// Phone number is required | |
$input['phone'] = trim($_POST['phone'] ?? ''); | |
if (0 == strlen($input['phone'])) { | |
$errors[] = 'Please enter a phone number.'; | |
} else { | |
// Be US-centric and ensure that the phone number contains | |
// at least 10 digits. Using ctype_digit() on each | |
// character is not the most efficient way to do this, | |
// but is logically straightforward and avoids | |
// regular expressions. | |
$digits = 0; | |
for ($i = 0; $i < strlen($input['phone']); $i++) { | |
if (ctype_digit($input['phone'][$i])) { | |
$digits++; | |
} | |
} | |
if ($digits < 10) { | |
$errors[] = 'Phone number needs at least ten digits.'; | |
} | |
} | |
return array($errors, $input); | |
} | |
function process_form4($input) | |
{ | |
// Access the global variable $db inside this function | |
global $db; | |
// Build up the query. No need to specify customer_id because | |
// the database will automatically assign a unique one. | |
$sql = 'INSERT INTO customers (name,phone,favorite_dish_id) ' . | |
'VALUES (?,?,?)'; | |
// Send the query to the database program and get all the rows back | |
try { | |
$stmt = $db->prepare($sql); | |
$stmt->execute(array($input['name'], $input['phone'], $input['dish_id'])); | |
print '<p>Inserted new customer.</p>'; | |
} catch (Exception $e) { | |
print "<p>Couldn't insert customer: {$e->getMessage()}.</p>"; | |
} | |
} | |
// The code relies on the FormHelper.php file discussed in Chapter 7. | |
// The customer-form.php file referenced, which displays the form HTML, contains: ?> | |
<form method="POST" action="<?= $form->encode($_SERVER['PHP_SELF']) ?>"> | |
<table> | |
<?php if ($errors) { ?> | |
<tr> | |
<td>You need to correct the following errors:</td> | |
<td> | |
<ul> | |
<?php foreach ($errors as $error) { ?> | |
<li><?= $form->encode($error) ?></li> | |
<?php } ?> | |
</ul> | |
</td> | |
<?php } ?> | |
<tr> | |
<tr> | |
<td>Name:</td> | |
<td><?= $form->input('text', ['name' => 'name']) ?> | |
</td> | |
</tr> | |
<tr> | |
<td>Phone Number:</td> | |
<td><?= $form->input('text', ['name' => 'phone']) ?></td> | |
</tr> | |
<tr> | |
<td>Favorite Dish:</td> | |
<td><?= $form->select($dishes, ['name' => 'dish_id']) ?></td> | |
</tr> | |
<tr> | |
<td colspan="2" align="center"> | |
<?= $form->input('submit', ['name' => 'add', 'value' => 'Add Customer']) ?> | |
</td> | |
</tr> | |
</table> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment