Below is the db connection class I came out with so far, but I am going to improve it by extending the PDO class itself,
$dsn is data source name. It handles your hostname for you. You use it like this:
$dsn = 'mysql:dbname=YOUR_DB_NAME;host=YOUR_HOSTNAME'
With the line $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
You have set exceptions to be raised when errors occur (which I like), so in your extended class you can handle errors in exception handlers. If you had a method called getAssoc in your extended PDO class then it would look like this:
/// Get an associative array of results for the sql.
public function getAssoc($sql, $params=array())
{
try
{
$stmt = $this->prepare($sql);
$params = is_array($params) ? $params : array($params);
$stmt->execute($params);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (Exception $e)
{
// Echo the error or Re-throw it to catch it higher up where you have more
// information on where it occurred in your program.
// e.g echo 'Error: ' . $e->getMessage();
throw new Exception(
__METHOD__ . 'Exception Raised for sql: ' . var_export($sql, true) .
' Params: ' . var_export($params, true) .
' Error_Info: ' . var_export($this->errorInfo(), true),
0,
$e);
}
}
I would concentrate on what the class needs to do rather than trying to re write the PDO. I had the same idea because i though it would simplify and stream line the code but it doesn't. You end up spending more time working out how to indirectly interface with the PDO.