Page 429 - Beginning PHP 5.3
P. 429
Chapter 13: Retrieving Data from MySQL with PHP
$members = array();
foreach ( $st- > fetchAll() as $row ) {
$members[] = new Member( $row );
}
$st = $conn- > query( “SELECT found_rows() AS totalRows” );
$row = $st- > fetch();
parent::disconnect( $conn );
return array( $members, $row[“totalRows”] );
} catch ( PDOException $e ) {
parent::disconnect( $conn );
die( “Query failed: “ . $e- > getMessage() );
}
}
public static function getMember( $id ) {
$conn = parent::connect();
$sql = “SELECT * FROM “ . TBL_MEMBERS . “ WHERE id = :id”;
try {
$st = $conn- > prepare( $sql );
$st- > bindValue( “:id”, $id, PDO::PARAM_INT );
$st- > execute();
$row = $st- > fetch();
parent::disconnect( $conn );
if ( $row ) return new Member( $row );
} catch ( PDOException $e ) {
parent::disconnect( $conn );
die( “Query failed: “ . $e- > getMessage() );
}
}
public function getGenderString() {
return ( $this- > data[“gender”] == “f” ) ? “Female” : “Male”;
}
public function getFavoriteGenreString() {
return ( $this- > _genres[$this- > data[“favoriteGenre”]] );
}
}
? >
First the script includes the DataObject class file so that it can derive the Member class from
DataObject . Next the class sets up the $data array keys, initializing each value to an empty string. Not
only does this let you see at - a - glance the data that the Member class works with, but it also enables the
DataObject class ’ s __construct() method to validate each field name that ’ s passed to it when
creating the object. If a field name is passed that isn ’ t in the $data array, it ’ s rejected.
The class also creates a private array, $_genres , to map the ENUM values of the favoriteGenre field
in the members table (for example, “ nonFiction “ ) to human - readable strings (such as “ Non - Fiction ” ).
391
9/21/09 9:12:04 AM
c13.indd 391
c13.indd 391 9/21/09 9:12:04 AM