SakhaliaNetHome PageMilitary HistoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Exercises (VIII)

PHP Exercise #17

Show data for selected element

Write a program that shows in a select menu all the dishes stored in the table. When the form is sent, the program must print all the information about the selected dish.

<?php
// Loads the form's auxiliary functions
require 'scripts/formhelpers.php';
// Connects with database
$db = mysqli_connect('insert_hostname_here','insert_username_here',
'insert_password_here','insert_databasename_here');
if (! $db) { die("Can't connect: " . mysqli_connect_error()); }
// Obtain the array of dishes from the database
$dish_names = array();
$sql = 'SELECT dish_name FROM dishes_2';
$q = mysqli_query($db, $sql);
if (mysqli_num_rows($q) > 0) {
while ($row = mysqli_fetch_object($q)) {
$dish_names[] = $row->dish_name;
}
} else {
print 'No dishes available.';
}
// Main logic for the form
// - If the form is sent, validate it and process it or show it again
// - If it is not sent, show it
if (! array_key_exists('_submit_check', $_POST)) {
$_POST['_submit_check'] = 0;
}
if ($_POST['_submit_check']) {
// If validate_form() returns errors, pass them to show_form()
if ($form_errors = validate_form()) {
show_form($form_errors);
} else {
// The data sent is valid, therefore, process it
process_form();
}
} else {
// The form had not been sent, therefore, show it
show_form();
}
function show_form($errors ='') {
global $db;
// If errors were passed, print them
if ($errors) {
print 'You need to correct the following errors: <ul><li>';
print implode('</li><li>',$errors);
print '</li></ul>';
}
// The beginning of the form
print '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
print '<table>';
// Dish select menu
print '<tr><td>Dish:</td><td>';
input_select('dish_name', $_POST, $GLOBALS['dish_names']);
print '</td></tr>';
// End of the form
print '<tr><td colspan="2"><input type="submit" value="Search Dishes">
</td></tr>';
print '</table>';
print '<input type="hidden" name="_submit_check" value="1"/>';
print '</form>';
}
function validate_form() {
$errors= array();
if (! array_key_exists($_POST['dish_name'], $GLOBALS['dish_names'])) {
$errors[] = 'Please select a valid dish.';
}
return $errors;
}
function process_form() {
global $db;
// Convert $_POST['dish_name'] (which is a number) into a name
$dish_name = $GLOBALS['dish_names'][$_POST['dish_name']];
$sql = "SELECT dish_id, dish_name, price, is_spicy
FROM dishes WHERE dish_name = '" . $dish_name . "'";
$q = mysqli_query($db, $sql);
$dish_info = mysqli_fetch_object($q);
if (count($dish_info) > 0) {
print '<ul>';
print "<li> ID: $dish_info->dish_id</li>";
print "<li> Name: $dish_info->dish_name</li>";
print "<li> Price: $dish_info->price</li>";
print "<li> Is Spicy: $dish_info->is_spicy</li>";
print '</ul>';
print nl2br("\n\n"); // Allows to show the form
show_form(); // after being sent
} else {
print 'No dish matches.';
}
}
?>
Dish: