Last active
December 11, 2015 22:19
-
-
Save alixaxel/4668904 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 | |
public static function DB($query = null) | |
{ | |
static $db = array(); | |
static $result = array(); | |
if (isset($db[self::$id], $query) === true) | |
{ | |
if (empty($result[self::$id][$hash = md5($query)]) === true) | |
{ | |
$result[self::$id][$hash] = $db[self::$id]->prepare($query); | |
} | |
if (is_object($result[self::$id][$hash]) === true) | |
{ | |
if ($result[self::$id][$hash]->execute(self::Flatten(array_slice(func_get_args(), 1))) === true) | |
{ | |
if (preg_match('~^(?:INSERT|REPLACE)\b~i', $query) > 0) | |
{ | |
$sequence = null; | |
if (strcmp('pgsql', $db[self::$id]->getAttribute(PDO::ATTR_DRIVER_NAME)) === 0) | |
{ | |
if (preg_match('~\bRETURNING\b~i', $query) > 0) | |
{ | |
return $result[self::$id][$hash]->fetchColumn(); | |
} | |
$sequence = sprintf('%s_id_seq', trim(ph()->Text->Regex($query, 'INTO\s*(["\w]+)', array(1, 0), 'i'), '"')); | |
} | |
return $db[self::$id]->lastInsertId($sequence); | |
} | |
else if (preg_match('~^(?:DELETE|UPDATE)\b~i', $query) > 0) | |
{ | |
return $result[self::$id][$hash]->rowCount(); | |
} | |
else if (preg_match('~^(?:CALL|DESC(?:RIBE)?|EXPLAIN|PRAGMA|SELECT|SHOW)\b~i', $query) > 0) | |
{ | |
return $result[self::$id][$hash]->fetchAll(PDO::FETCH_ASSOC); | |
} | |
return true; | |
} | |
} | |
return false; | |
} | |
else if (preg_match('~^(?:firebird|mysql|pgsql|sqlite):~', $query) > 0) | |
{ | |
try | |
{ | |
$auth = array_slice(func_get_args(), 1, 2); | |
if (preg_match('~^(?:firebird|sqlite):~', $query) > 0) | |
{ | |
$query = preg_replace('~^([^:]+):(?:/{2})?(.+)$~', '$1:$2', $query); | |
} | |
else if (preg_match('~^(?:mysql|pgsql):~i', $query) > 0) | |
{ | |
$query = preg_replace('~^([^:]+):/{0,2}([^:/]+)(?::(\d+))?/(\w+)/?$~', '$1:host=$2;port=$3;dbname=$4', $query); | |
} | |
$db[self::$id] = new PDO($query, array_shift($auth), array_shift($auth)); | |
if (strcmp('mysql', $db[self::$id]->getAttribute(PDO::ATTR_DRIVER_NAME)) === 0) | |
{ | |
self::DB('SET time_zone = ?;', date_default_timezone_get()); | |
self::DB('SET NAMES ? COLLATE ?;', 'utf8', 'utf8_unicode_ci'); | |
} | |
$db[self::$id]->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); | |
} | |
catch (PDOException $e) | |
{ | |
return false; | |
} | |
} | |
return (isset($db[self::$id]) === true) ? $db[self::$id] : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also wanted to mention this code for MySQL prepared statements