Prev | Current Page 164 | Next

Emilian Balanescu and Cristian Darie

"Beginning PHP and MySQL E-Commerce: From Novice to Professional, Second Edition"


// Class providing generic data access functionality
class DatabaseHandler
{
// Hold an instance of the PDO class
private static $_mHandler;
CHAPTER 4 ?–  CREATING THE PRODUCT CATALOG: PART 1 91
// Private constructor to prevent direct creation of object
private function __construct()
{
}
// Return an initialized database handler
private static function GetHandler()
{
// Create a database connection only if one doesn't already exist
if (!isset(self::$_mHandler))
{
// Execute code catching potential exceptions
try
{
// Create a new PDO class instance
self::$_mHandler =
new PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD,
array(PDO::ATTR_PERSISTENT => DB_PERSISTENCY));
// Configure PDO to throw exceptions
self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
}
// Return the database handler
return self::$_mHandler;
}
}
?>
3. Add the Close() method to the DatabaseHandler class. This method will be called to close the database
connection:
// Clear the PDO class instance
public static function Close()
{
self::$_mHandler = null;
}
CHAPTER 4 ?–  CREATING THE PRODUCT CATALOG: PART 1 92
4. Add the Execute() method to the DatabaseHandler class. This method uses the PDOStatement::
execute() to run queries that don??™t return records (INSERT, DELETE, or UPDATE queries):
// Wrapper method for PDOStatement::execute()
public static function Execute($sqlQuery, $params = null)
{
// Try to execute an SQL query or a stored procedure
try
{
// Get the database handler
$database_handler = self::GetHandler();
// Prepare the query for execution
$statement_handler = $database_handler->prepare($sqlQuery);
// Execute query
$statement_handler->execute($params);
}
// Trigger an error if an exception was thrown when executing the SQL query
catch(PDOException $e)
{
// Close the database handler and trigger an error
self::Close();
trigger_error($e->getMessage(), E_USER_ERROR);
}
}
5.


Pages:
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
drukarki fiskalne kraków willa karmazyn międzyzdroje www.books61.hobbitstory.com terapia magnetyczna Informacje o hostingu