Skip to content

Instantly share code, notes, and snippets.

@randomecho
Last active December 18, 2015 09:38
Show Gist options
  • Save randomecho/5762430 to your computer and use it in GitHub Desktop.
Save randomecho/5762430 to your computer and use it in GitHub Desktop.
Database hookup for wrapping around PDO
<?php
/**
* Database hookup for wrapping around PDO
*
* @author Soon Van - randomecho.com
* @copyright 2013 Soon Van
* @license http://www.opensource.org/licenses/BSD-3-Clause
*/
class DB {
public function execute($sql, $params = false, $single = true, $readonly = true)
{
if ($params === false)
{
$params = array();
}
$pdo = DB::hookup();
$raw_sql = substr($sql, 0, 6);
$sql = $pdo->prepare($sql);
try
{
$sql->execute($params);
}
catch (Exception $e)
{
$bork_mess = $e->getMessage();
if (cog::localhost())
{
cog::dump($sql);
cog::dump($params);
}
else
{
echo 'Oh dear. Something bad happened.';
cog::mailer('Database call fail', $bork_mess);
}
}
if ($readonly)
{
$result = ($single) ? $sql->fetch() : $sql->fetchAll();
}
else
{
if ($raw_sql == 'insert')
{
$result = $pdo->lastInsertId();
}
else
{
if ($single)
{
$result = ($sql->rowCount() == 1) ? true : false;
}
else
{
$result = $sql->rowCount();
}
}
}
return $result;
}
public function hookup()
{
if ( ! class_exists('PDO'))
{
cog::mailer('PDO not loaded');
echo 'Temporarily cannot connect to the database. Working on it.';
}
try
{
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_PERSISTENT => true));
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('set names utf8');
return $pdo;
}
catch (PDOException $e)
{
$bork_mess = $e->getMessage();
if ( ! cog::localhost())
{
cog::mailer('Database fail', $bork_mess);
$bork_mess = 'That is just not quite cricket.';
}
cog::dump("Error: " . $bork_mess, 1);
}
}
function unhook($pdo)
{
$pdo = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment