Skip to content

Instantly share code, notes, and snippets.

@Mwamitovi
Created January 29, 2025 06:44
Show Gist options
  • Save Mwamitovi/fbb2c4f1ef014a6822bd95d0f010b593 to your computer and use it in GitHub Desktop.
Save Mwamitovi/fbb2c4f1ef014a6822bd95d0f010b593 to your computer and use it in GitHub Desktop.
<?php
// Chapter-12: Exercises
// Question-1
// 1. This program has a syntax error in it:
$name = 'Umberto';
function say_hello() {
print 'Hello, ';
// print global $name;
}
say_hello();
// Without running the program through the PHP engine,
// figure out what the parse error that gets printed when the engine tries to run the program looks like.
// What change must you make to the program to get it to run properly and print Hello, Umberto?
// Answer-1
// The keyword global should not be in line 5, so the parse error should report that unexpected keyword.
// The actual parse error is:
// PHP Parse error: syntax error, unexpected 'global' (T_GLOBAL) in debugging-12.php on line 5
// To make the program run properly, change the line print global $name; to print
// $GLOBALS['name'];. Or, you can add global name; as the first line of the function and then change print global $name; to print $name;.
// Question-2
// 2. Modify the validate_form() function in your answer to Exercise 3 in Chapter 7 (see “Exercise 3” on page 345)
// so that it prints in the web server error log the names and values of all of the submitted form parameters.
// Answer-2
function validate_form()
{
$input = array();
$errors = array();
// turn on output buffering
ob_start();
// dump all the submitted data
var_dump($_POST);
// capture the generated "output"
$output = ob_get_contents();
// turn off output buffering
ob_end_clean();
// send the variable dump to the error log
error_log($output);
// op is required
$input['op'] = $GLOBALS['ops'][$_POST['op']] ?? '';
if (!in_array($input['op'], $GLOBALS['ops'])) {
$errors[] = 'Please select a valid operation.';
}
// num1 and num2 must be numbers
$input['num1'] = filter_input(INPUT_POST, 'num1', FILTER_VALIDATE_FLOAT);
if (is_null($input['num1']) || ($input['num1'] === false)) {
$errors[] = 'Please enter a valid first number.';
}
$input['num2'] = filter_input(INPUT_POST, 'num2', FILTER_VALIDATE_FLOAT);
if (is_null($input['num2']) || ($input['num2'] === false)) {
$errors[] = 'Please enter a valid second number.';
}
// can't divide by zero
if (($input['op'] == '/') && ($input['num2'] == 0)) {
$errors[] = 'Division by zero is not allowed.';
}
return array($errors, $input);
}
// Question-3
// 3. Modify your answer to Exercise 4 in Chapter 8 (see “Exercise 4” on page 357) to use a custom database
// error-handling function that prints out different messages in the web browser and in the web server error log.
// The error-handling function should make the program exit after it prints the error messages.
// Answer-3
// At the top of the program, this code defines an exception handler and sets it up to be called on unhandled exceptions:
function exceptionHandler($ex)
{
// Log the specifics to the error log
error_log("ERROR: " . $ex->getMessage());
// Print something less specific for users to see
// and exit
die("<p>Sorry, something went wrong.</p>");
}
set_exception_handler('exceptionHandler');
// Question-4
// Then the try/catch blocks can be removed from the two places they are used (once around creating the PDO object and once in process_form())
// because the exceptions will be handled by the exception handler.
// 4. The following program is supposed to print out an alphabetical list of all the customers in the table from
// Exercise 4 in Chapter 8 (see “Exercise 4” on page 357). Find and fix the errors in it.
// Connect to the database
try {
} catch ($e) {
$db = new PDO('sqlite::/tmp/restaurant.db');
die("Can't connect: " . $e->getMessage());
}
// Set up exception error handling
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set up fetch mode: rows as arrays
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// Get the array of dish names from the database
$dish_names = array();
$res = $db->query('SELECT dish_id,dish_name FROM dishes');
foreach ($res->fetchAll() as $row) {
$dish_names[ $row['dish_id']]] = $row['dish_name'];
}
$res = $db->query('SELECT ** FROM customers ORDER BY phone DESC');
$customers = $res->fetchAll();
if (count($customers) = 0) {
print "No customers.";
} else {
print '<table>';
print '<tr><th>ID</th><th>Name</th><th>Phone</th>
<th>Favorite Dish</th></tr>';
foreach ($customers as $customer) {
printf("<tr><td>%d</td><td>%s</td><td>%f</td><td>%s</td></tr>\n"
$customer['customer_id'],
htmlentities($customer['customer_name']),
$customer['phone'],
$customer['favorite_dish_id']);
}
print '</table>';
// Answer-4
// • Line 4: Change :: to : in the DSN.
// • Line 5: Change catch ($e) to catch (Exception $e).
// • Line 16: Change $row['dish_id']] to $row['dish_id'] as the key to look up in the $dish_names array.
// • Line 18: Change ** to * in the SQL query.
// • Line 20: Change = to ==.
// • Line 26: Change the third format specifier from %f to %s—$customer['phone'] is a string.
// • Line 30: Change $customer['favorite_dish_id'] to $dish_names [$customer['favorite_dish_id']] so that
// the dish ID is translated into the name of the corresponding dish.
// • Line 33: Insert a } to match the opening { in line 22.
// The complete corrected program is:
// Connect to the database
try {
$db = new PDO('sqlite:/tmp/restaurant.db');
} catch (Exception $e) {
die("Can't connect: " . $e->getMessage());
}
// Set up exception error handling
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set up fetch mode: rows as arrays
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// Get the array of dish names from the database
$dish_names = array();
$res = $db->query('SELECT dish_id,dish_name FROM dishes');
foreach ($res->fetchAll() as $row) {
$dish_names[$row['dish_id']] = $row['dish_name'];
}
$res = $db->query('SELECT * FROM customers ORDER BY phone DESC');
$customers = $res->fetchAll();
if (count($customers) == 0) {
print "No customers.";
} else {
print '<table>';
print '<tr><th>ID</th><th>Name</th>
<th>Phone</th><th>Favorite Dish</th></tr>';
foreach ($customers as $customer) {
printf(
"<tr><td>%d</td><td>%s</td><td>%s</td><td>%s</td></tr>\n",
$customer['customer_id'],
htmlentities($customer['customer_name']),
$customer['phone'],
$dish_names[$customer['favorite_dish_id']]
);
}
print '</table>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment