Specifications
The functions get_categories() and display_categories() are in the function libraries
book_fns.php and output_fns.php, respectively. The function get_categories() returns an
array of the categories in the system, which we then pass to display_categories(). Let’s
look at the code for get_categories(). It is shown in Listing 25.3.
LISTING 25.3 get_categories() Function from output_fns.php—Function That Retrieves a
Category List from the Database
function get_categories()
{
// query database for a list of categories
$conn = db_connect();
$query = “select catid, catname
from categories”;
$result = @mysql_query($query);
if (!$result)
return false;
$num_cats = @mysql_num_rows($result);
if ($num_cats ==0)
return false;
$result = db_result_to_array($result);
return $result;
}
As you can see, this function connects to the database and retrieves a list of all the category
IDs and names. We have written and used a function called db_result_to_array(), located in
db_fns.php. This function is shown in Listing 25.4. It takes a MySQL result identifier and
returns a numerically indexed array of rows, where each row is an associative array.
LISTING 25.4 db_result_to_array() Function from db_fns.php—Function That Converts a
MySQL Result Identifier into an Array of Results
function db_result_to_array($result)
{
$res_array = array();
for ($count=0; $row = @mysql_fetch_array($result); $count++)
$res_array[$count] = $row;
return $res_array;
}
Building Practical PHP and MySQL Projects
P
ART V
552
31 7842 CH25 3/6/01 3:38 PM Page 552










