Created
August 17, 2013 06:01
-
-
Save chrisforrence/6255518 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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