Why isn't such data stored? The answer is usually that it is redundant: storing it adds no more information to the database. The down side is that you need calculations to recreate output when it is needed. In this section, this is illustrated with a simple example that shows the per-bottle saving when a user purchases more than a dozen bottles.
Returning to the script in Example 4-10, having produced a complete heading that now includes the wine variety, we produce the wine review in the script as before. However, rather than finishing with a simple bottle
case_cost, we do some calculations that show users any savings through buying a case:
$dozen_saving = $row["cost"] - ($row["case_cost"]/12); if ($dozen_saving > 0) printf("Save <b>%-.2f</b> per bottle when buying a dozen\n", $dozen_saving);
$row["cost"] is the cost of a single bottle, and
$row["case_cost"] is the cost of a case. Since a case contains 12 bottles, it follows that the cost of 1 bottle in the case is
$row["case_cost"]/12. The difference between the price of a single bottle and the price of bottle that comes in a case is then:
The result is stored in
A saving is printed out only if there is one; that is, when
$dozen_saving is greater than zero. In the case where buying a dozen bottles at once costs the same as 12 separate purchases (or maybe more!), nothing is shown.
printf is used in preference to
echo, so that you can include the formatting string
%-.2f to show exactly two decimal places (that is, the cents of the
There are many examples of calculations that are performed on the raw data from the database to present information to the user in our winestore. These include calculating order totals, discounts, receipt information, delivery charges, and so on. Elementary mathematics is a common component of most web database applications; it's used throughout later examples.updated