Example 8-4 shows the backend page that allows administrators to add categories to the listing service. The input fields for adding a new record appear after a dump of the current data. The administrator fills in the form and presses the Add Category button, and the page redisplays with the new record. If any of the three fields are not filled in, the page displays an error message.
// determine the length of each input field $len_cat_id = strlen($_REQUEST['Cat_ID']); $len_cat_tl = strlen($_REQUEST['Cat_Title']); $len_cat_de = strlen($_REQUEST['Cat_Desc']);
// validate and insert if the form script has been // called by the Add Category button if ($add_record == 1) { if (($len_cat_id > 0) and ($len_cat_tl > 0) and ($len_cat_de > 0)){ $sql = "insert into categories (category_id, title, description)"; $sql .= " values ('$Cat_ID', '$Cat_Title', '$Cat_Desc')"; $result = $db->query($sql); $db->commit(); } else { echo "<p>Please make sure all fields are filled in "; echo "and try again.</p>\n"; } }
// list categories reporting section
// query all records in the table after any // insertion that may have occurred above $sql = "select * from categories"; $result = $db->query($sql); ?>
<?php // display any records fetched from the database // plus an input line for a new category while ($row = $result->fetchRow()){ echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td></tr>\n"; } ?>
When the administrator submits a new category, we construct a query to add the category to the database. Another query displays the table of all current categories. Figure 8-4 shows the page with five records loaded.