Skip to content

Instantly share code, notes, and snippets.

@artursmirnov
Last active December 15, 2015 20:19
Show Gist options
  • Save artursmirnov/5317362 to your computer and use it in GitHub Desktop.
Save artursmirnov/5317362 to your computer and use it in GitHub Desktop.
Database access class
<?php
/**
* Database access class
*
* @author sag
*/
class DB {
/**
* Collection of database connections
* @var Array connections collection
*/
protected static $_instance = array();
/**
* Current database connection object
* @var PDO connection object
*/
public $conn;
/**
* Creates connection by given alias (implements singleton)
* @param String $alias Database connection alias
*/
private function __construct($alias){
$cfg = Config::getInstance();
$connString = $cfg->get("db.".$alias.".connString");
$user = $cfg->get("db.".$alias.".user");
$pass = $cfg->get("db.".$alias.".pass");
try{
$this->conn = new PDO($connString, $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"));
} catch (PDOException $e) {
return null;
}
}
private function __clone(){}
/**
* Getting Database connection instance by alias (implements Singleton)
* @param String $alias Database connection alias
* @return PDO connection object
*/
public static function getInstance($alias = "serv"){
if (empty(self::$_instance[$alias])) {
try {
self::$_instance[$alias] = new self($alias);
} catch (PDOException $e) {
return null;
}
}
return self::$_instance[$alias];
}
/**
* Execute 'SELECT-type' SQL-query by query alias (SQL-queries are stored in static class DBQuery)
* @param String $queryAlias SQL-query alias (= DBQuery key)
* @param Array $params Associative array with parameters for binding in prepared statement
* @param Mixed $fetchTo Type of return value. Could be object, class name or empty (to fetch into stdClass object)
* @param Array $constr Array of parameters to pass to new Class instance constructor
* @throws Exception
* @return Mixed result depending on $fetchTo parameter
*/
public function query($queryAlias, $params = null, $fetchTo = null, $constr = null) {
if (!$this->conn)
throw new Exception ("Database connection error");
// getting query by alias
$query = DBQuery::getQuery("get.".$queryAlias);
if (!empty ($params)) {
// replacing array parameters to IN-statement (exmpl: WHERE value IN ('1','3','5') )
foreach ($params as $param => $value) {
if (is_array($value)) {
$query = str_replace(':'.$param, "'".implode("', '", $value)."'", $query);
unset($params[$param]);
}
}
}
// creating prepared statement
$stmt = $this->conn->prepare($query);
if (!empty ($params)) {
// binding parameters to prepared statement
foreach ($params as $param => $value) {
$type = null;
if (is_int($value)) $type = PDO::PARAM_INT;
if (is_string($value)) $type = PDO::PARAM_STR;
if (!is_array($value)) $stmt->bindValue($param, $value, $type);
}
}
// executing statement
if (!@$stmt->execute()) {
throw new Exception("Invalid SQL-query or wrong parameters");
}
// fetching result
if (!empty($fetchTo)) {
if (is_string($fetchTo)) { // $fetchTo is a class name
$stmt->setFetchMode(PDO::FETCH_CLASS, $fetchTo, $constr);
} elseif (is_object($fetchTo)) { // $fetchTo is an object
$stmt->setFetchMode(PDO::FETCH_INTO, $fetchTo);
}
} else { // $fetchTo is empty
$stmt->setFetchMode(PDO::FETCH_OBJ);
}
return $stmt->fetchAll();
}
/**
* Execute 'INSERT/UPDATE/DELETE-type' SQL-query by alias (SQL-queries are stored in static class DBQuery)
* @param String $queryAlias SQL-query alias (= DBQuery key)
* @param Array $params Associative array with parameters for binding in prepared statement
* @throws Exception
* @return int Amount of updated/deleted/inserted records
*/
public function exec($queryAlias, $params = null) {
if (!$this->conn)
throw new Exception ("Database connection error");
//getting SQL-query
$query = DBQuery::getQuery("set.".$queryAlias);
// creating prepared statement
$stmt = $this->conn->prepare($query);
if (!empty ($params)) {
// binding parameters
foreach ($params as $param => $value) {
$value = strip_tags($value);
$stmt->bindValue($param, $value);
}
}
// executing statement
if (!@$stmt->execute())
throw new Exception("Invalid SQL-query or wrong parameters");
return $stmt->rowCount();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment