Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
<?php
/**
* Database Connection class.
*
* Example:
* $dbi = DBConnection::getInstance();
* $q = "SELECT * FROM Users WHERE Username=?";
* $a = array($_GET['username']);
* $users = $dbi->query($q, $a);
* if($users['count'] > 0)
* {
* foreach($users['result'] as $row)
* {
* echo $row['username'] . '<br />';
* }
* }
* $dbi = null;
*
* @author Chris Forrence
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @version 1.0
*/
class DBConnection extends PDO
{
private static $instance = null;
private $connection;
private $dbName = "db_name";
private $dbHost = "localhost";
private $dbUser = "db_user";
private $dbPass = "db_pass";
public function getConnection()
{
return $this->connection;
}
public function __construct()
{
try
{
$this->connection = new PDO("mysql:dbname=" . $this->dbName . ";host=" . $this->dbHost, $this->dbUser, $this->dbPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true));
}
catch(PDOException $e)
{
error_log($e->getMessage());
}
}
public static function getInstance()
{
if(self::$instance == null || empty(self::$instance))
{
try
{
self::$instance = new DBConnection();
}
catch(PDOException $p)
{
error_log("PDOException caught: " . $p->getMessage());
}
}
return self::$instance;
}
public function execute($query, $args = array())
{
$tokens = explode(" ", $query);
try
{
$this->connection->beginTransaction();
$sth = $this->connection->prepare($query);
if(empty($args))
{
$sth->execute();
}
else
{
$sth->execute($args);
}
if(strtoupper($tokens[0]) == "SELECT")
{
$sth->setFetchMode(PDO::FETCH_ASSOC);
$ret = $sth->fetchAll();
}
else if(strtoupper($tokens[0]) == "INSERT")
{
$ret = $this->getLastInsertID();
}
else
{
$ret = $sth->rowCount();
}
$this->connection->commit();
}
catch(PDOException $e)
{
error_log('Query failed: ' . $e->getMessage());
error_log('Query : ' . $query);
$this->connection->rollBack();
$ret = -1;
}
return $ret;
}
private function getLastInsertID()
{
return $this->connection->lastInsertId();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.