Commit 474f9814 authored by Peter Göbel's avatar Peter Göbel

added pdo class files

parent 01e7f1e8
# PDO class for PHP
- See index.php for usage examples
- Change database connection credentials in class.database.php
\ No newline at end of file
<?php
/*
* PDO class
* inspired by http://pastebin.com/9pyPrQfk
*/
class Database
{
protected static $dbConf = array(
"default" => array(
"type" => "mysql",
"config" => "host=localhost;dbname=XXX;port=XXX",
"user" => "XXX",
"password" => "XXX")
);
protected $active = false;
protected $dbHandle = null;
protected $lastInsertId = false;
protected $rowCount = false;
protected $queryCounter = 0;
protected static $instances = array();
public static function get($active = "default")
{
if (!isset(self::$dbConf[$active])) {
throw new Exception("Unexisting db-config $active");
}
if (!isset(self::$instances[$active]))
self::$instances[$active] = new Database($active);
return self::$instances[$active];
}
private function __clone()
{
}
protected function __construct($active)
{
if (!isset(self::$dbConf[$active]))
throw new PDOException("No supported connection scheme");
$dbConf = self::$dbConf[$active];
try
{
//Connect
if ($active == 'default') {
$db = new PDO($dbConf['type'].":".$dbConf['config'],$dbConf['user'],$dbConf['password']);
} else if ($active == 'sqlite') {
$db = new PDO($dbConf['type'].":".$dbConf['config']);
} else {
throw new PDOException("No Database connection");
}
//error behaviour
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($active == 'default') {
$db->query("set character set utf8");
$db->query("set names utf8");
}
$this->dbHandle = $db;
$this->active = $active; //mark as active
} catch (PDOException $ex)
{
throw new PDOException("Connection Exception: " . $ex->getMessage());
}
}
public function disconnect()
{
$this->dbHandle = null;
unset(self::$instances[$this->active]);
}
public function getHandle()
{
return $this->dbHandle;
}
public function lastInsertId()
{
return $this->lastInsertId;
}
public function rowCount()
{
return $this->rowCount;
}
protected function _query($qry, array $params, $type)
{
if (in_array($type, array("insert", "select", "update", "delete")) === false)
throw new Exception("Unsupported Query Type");
$this->lastInsertId = false;
$this->rowCount = false;
$stmnt = $this->dbHandle->prepare($qry);
try
{
$success = (count($params) !== 0) ? $stmnt->execute($params) : $stmnt->execute();
$this->queryCounter++;
if (!$success)
return false;
if ($type === "insert")
$this->lastInsertId = $this->dbHandle->lastInsertId();
$this->rowCount = $stmnt->rowCount();
return ($type === "select") ? $stmnt : true;
} catch (PDOException $ex)
{
throw new PDOException("PDO-Exception: " . $ex->getMessage());
}
}
protected function getQueryType($qry)
{
list($type, ) = explode(" ", strtolower($qry), 2);
return $type;
}
public function delete($qry, array $params = array())
{
if (($type = $this->getQueryType($qry)) !== "delete")
throw new Exception("Incorrect Delete Query");
return $this->_query($qry, $params, $type);
}
public function update($qry, array $params = array())
{
if (($type = $this->getQueryType($qry)) !== "update")
throw new Exception("Incorrect Update Query");
return $this->_query($qry, $params, $type);
}
public function insert($qry, array $params = array())
{
if (($type = $this->getQueryType($qry)) !== "insert")
throw new Exception("Incorrect Insert Query");
return $this->_query($qry, $params, $type);
}
public function select($qry, array $params = array())
{
if (($type = $this->getQueryType($qry)) !== "select")
throw new Exception("Incorrect Select Query");
if ($stmnt = $this->_query($qry, $params, $type))
{
return $stmnt->fetchAll(PDO::FETCH_ASSOC);
} else
{
return false;
}
}
public function selectSingle($qry, array $params = array(), $field = false)
{
if (($type = $this->getQueryType($qry)) !== "select")
throw new Exception("Incorrect Select Query");
if ($stmnt = $this->_query($qry, $params, $type))
{
$res = $stmnt->fetch(PDO::FETCH_ASSOC);
return ($field === false) ? $res : $res[$field];
} else
{
return false;
}
}
public function query($qry)
{
$this->lastInsertId = false;
$this->rowCount = false;
$this->rowCount = $this->dbHandle->exec($qry);
$this->queryCounter++;
}
public function getQueryCounter()
{
return $this->queryCounter;
}
public function quote($str)
{
return $this->dbHandle->quote($str);
}
}
\ No newline at end of file
<?php
class Example {
protected $_db;
public function __construct(Database $db)
{
$this->_db = $db;
}
public function getStuff() {
$sql = "SELECT * FROM example_table";
$data = $this->_db->select($sql);
return $data;
}
public function getSingleStuff() {
$sql = "SELECT * FROM example_table";
$data = $this->_db->selectSingle($sql);
return $data;
}
public function getStuffWithParams($id) {
$params = array(
':id' => $id);
$sql = "SELECT * FROM example_table WHERE foo = :id";
$data = $this->_db->select($sql,$params);
return $data;
}
public function insertStuff($id) {
$params = array(
':id' => $id);
$sql = "INSERT INTO example_table (foo) VALUES (:id)";
$data = $this->_db->insert($sql,$params);
return $data;
}
public function updateStuff($id) {
$params = array(
':id' => $id);
$sql = "UPDATE example_table SET bar = :id WHERE foo = :id";
$data = $this->_db->update($sql,$params);
return $data;
}
public function deleteStuff($id) {
$params = array(
':id' => $id);
$sql = "DELETE FROM example_table WHERE foo =:id";
$data = $this->_db->delete($sql,$params);
return $data;
}
}
\ No newline at end of file
<?php
// sample usage
require_once('class.database.php');
require_once('class.example.php');
$db = Database::get('default');
$obj = new Example($db);
// get data
$data = $obj->getStuff();
// insert data
$foo = 'bar';
$obj->insertStuff($foo);
// update data
$foo = 'bar';
$obj->updateStuff($foo);
// delete data
$foo = 'bar';
$obj->deleteStuff($foo);
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment