SakhaliaNetHome PageSahara TerritoryVorKutaAcceptance of cookiesAcceptance of cookies

PHP Tutorial :: Exercises (VII)

PHP Exercise #15

Make list from database table

Write a program that shows all the dishes stored in the table, ordered by price.

<?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()); }
$sql = 'SELECT dish_name, price FROM dishes_2 ORDER BY price';
$q = mysqli_query($db, $sql);
if (mysqli_num_rows($q) > 0) {
print '<ul>';
while ($dish = mysqli_fetch_object($q)) {
print "<li>$dish->dish_name ($dish->price)</li>";
}
print '</ul>';
} else {
print 'No dishes available.';
}
?>
  • Walnut Bun (1.00)
  • Red Bean Bun (1.00)
  • Dried Mulberries (3.00)
  • Cashew Nuts and White Mushrooms (4.95)
  • General Tso's Chicken (5.50)
  • Eggplant with Chili Sauce (6.50)

PHP Exercise #16

Search dishes by minimum price

Write a program that asks for a minimum price and returns the names and prices of all the dishes whose price is at least the price sent.

<?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()); }
// 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 ='') {
// If the form has been sent, obtain the default values
// of the parameters sent
if ($_POST['_submit_check']) {
$defaults = $_POST;
} else {
// If not, set our own default values
$defaults = array('min_price' => '5.00');
}
// If errors were passed, put them in $error_text (with HTML code)
if (is_array($errors)) {
$error_text = '<tr><td>You need to correct the following errors:';
$error_text .= '</td><td><ul><li>';
$error_text .= implode('</li><li>',$errors);
$error_text .= '</li></ul></td></tr>';
} else {
// If there were no errors, then $error_text is empty
$error_text = '';
}
// Exit PHP mode to facilitate the visualization of all the HTML tags
?>
<form method="post" action="<?php print $_SERVER['PHP_SELF']; ?>">
<table>
<?php print $error_text; ?>
<tr><td>Minimum Price:</td>
<td><?php input_text('min_price', $defaults); ?></td></tr>
</td></tr>
<tr><td colspan="2" align="center">
<?php input_submit('search','Search'); ?>
</td></tr>
</table>
<input type="hidden" name="_submit_check" value="1"/>
</form>
<?php
} // The end of show_form()()
function validate_form() {
$errors = array();
// The minimum price must be a valid number
if (! is_numeric($_POST['min_price'])) {
$errors[] = 'Please enter a valid minimum price.';
} elseif ($_POST['min_price'] <=0) {
$errors[] = 'Please enter a price greater than 0.';
}
return $errors;
}
function process_form() {
// Accesses the global variable $db inside this function
global $db;
// Creates the query
$sql = 'SELECT dish_name, price, is_spicy FROM dishes_2 WHERE ';
// Adds minimum price to the query
$sql .= "price >= '" .
mysqli_real_escape_string($db, $_POST['min_price']) . "' ";
// We use mysqli_real_escape_string() and strtr() to prevent that
// wildcards facilitated by the user can work
// Sends the query to the database program and obtain all the rows
$q = mysqli_query($db, $sql);
if (mysqli_num_rows($q) == 0) {
print 'No dishes matched.';
print nl2br("\n\n"); // Permite visualizar el formulario
show_form(); // despu├ęs de ser enviado
} else {
print '<table>';
print '<tr><th>Dish Name</th><th>Price</th></tr>';
while ($dish = mysqli_fetch_object($q)) {
printf('<tr><td>%s</td><td>$%.02f</td></tr>',
htmlentities($dish->dish_name), $dish->price);
}
print '</table>';
print nl2br("\n\n"); // Allows to show the form
show_form(); // after being sent
}
}
?>
Minimum Price: