Prev | Current Page 160 | Next

Emilian Balanescu and Cristian Darie

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


Although it doesn??™t do it by default, PDO can be instructed to generate exceptions in case something goes
wrong when executing an SQL command or opening a database connection, like this:
// Create a new PDO class instance
$handler = new PDO( ... );
// Configure PDO to throw exceptions
self::$_mHandler->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
We catch any exceptions the data access code may throw, and we pass the error details to
the error-handling code you wrote in Chapter 3. The following code snippet shows a short
method with this functionality implemented:
// Wrapper method for PDOStatement::fetch()
public static function GetRow($sqlQuery, $params = null,
$fetchStyle = PDO::FETCH_ASSOC)
{
// Initialize the return value to null
$result = 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 the query
$statement_handler->execute($params);
// Fetch result
$result = $statement_handler->fetch($fetchStyle);
}
CHAPTER 4 ?–  CREATING THE PRODUCT CATALOG: PART 1 89
// 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);
}
// Return the query results
return $result;
}
Issuing Commands Using the Connection
After opening the connection, you??™re now at the stage we??™ve been aiming for from the start:
executing SQL commands through the connection.


Pages:
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
Miami Sound Machine fajna muza DC++ Ultra Speed Mattafix George Michael