13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Implementing the Online Catalog<br />

621<br />

This script is similar in structure to the index page, except that you retrieve books<br />

instead of categories.<br />

You start with session_start() as usual <strong>and</strong> then convert the category ID you have<br />

been passed into a category name by using the get_category_name() function as follows:<br />

$name = get_category_name($catid);<br />

This function, shown in Listing 28.7, looks up the category name in the database.<br />

Listing 28.7 get_category_name() Function from book_fns.php—Function That<br />

Converts a Category ID to a Category Name<br />

function get_category_name($catid) {<br />

// query database for the name for a category id<br />

$conn = db_connect();<br />

$query = "select catname from categories<br />

where catid = '".$catid."'";<br />

$result = @$conn->query($query);<br />

if (!$result) {<br />

return false;<br />

}<br />

$num_cats = @$result->num_rows;<br />

if ($num_cats == 0) {<br />

return false;<br />

}<br />

$row = $result->fetch_object();<br />

return $row->catname;<br />

}<br />

After you have retrieved the category name, you can render an HTML header <strong>and</strong> proceed<br />

to retrieve <strong>and</strong> list the books from the database that fall into your chosen category,<br />

as follows:<br />

$book_array = get_books($catid);<br />

display_books($book_array);<br />

The functions get_books() <strong>and</strong> display_books() are extremely similar to the<br />

get_categories() <strong>and</strong> display_categories() functions, so we do not go into them<br />

here.The only difference is that you retrieve information from the books table rather<br />

than the categories table.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!