Source code of dbAdd2.php
<html>
<head>
<title>Updating information in a database</title>
</head>
<body>
<h2>Updating Prices</h2>
<?php
// Get form data
$item_id = $_REQUEST['item_id'];
$color = $_REQUEST['color'];
$inv_size = $_REQUEST['inv_size'];
$inv_price = $_REQUEST['inv_price'];
$allLines = file("mysql.txt");
$password = trim($allLines[0]);
$dbLink = mysql_connect("localhost", "tboegel", $password);
mysql_select_db("clearwater", $dbLink);
// We need to be extremely careful any time we get information from
// a user, to make sure that the data they have provided is valid.
// We should _never_ just take input from a text box and insert it
// into a query
// Let's cast item_id as an int, and make sure it's greater than zero
$item_id = (int) $item_id;
if (is_finite($item_id) && $item_id > 0) {
$valid_item = true;
} else {
$valid_item = false;
}
// Let's make sure color is a string of 1-50 letters
if (ereg("^[[:alpha:]]{1,50}$", $color)) {
$valid_color = true;
} else {
$valid_color = false;
}
// Perform a similar check on size (but allow for zero character sizes,
// and allow for both letters and digits
if (ereg("^[[:alnum:]]{0,50}$", $inv_size)) {
$valid_size = true;
} else {
$valid_size = false;
}
// Finally, check price:
$inv_price = (float) $inv_price;
if (is_finite($inv_price) && $inv_price > 0 && $inv_price <= 999999.99) {
$valid_price = true;
} else {
$valid_price = false;
}
if ($valid_item && $valid_color && $valid_size && $valid_price) {
// Generate and execute the insert query.
// Since this is a new item, I'll say that the quantity on hand is zero
// I won't insert a value into the inv_id field, since
// auto_increment will assign a new value for it
$query = "INSERT INTO inventory "
. "(item_id, color, inv_size, inv_price, inv_qoh) VALUES "
. "($item_id, '$color', '$inv_size', $inv_price, 0)";
mysql_query($query, $dbLink);
if (mysql_affected_rows() == 1) {
print "<p>The item has been entered</p>";
} else {
print "<p>The item has not been entered</p>";
}
} else {
// I could look at the various $valid_ variables to print out a more
// meaningful error message, or even re-print the form, with arrows
// pointing to the values that were invalid
print "<p>There is an error with the values you are trying to insert.</p>";
}
mysql_close($dbLink);
?>
<p><a href='dbAdd1.php'>Add another item</a></p>
<p><a href='dbUpdate1.php'>Look at the price list</a></p>
</body>
</html>