Skip to content

Instantly share code, notes, and snippets.

@SenpaiSilver
Last active August 29, 2015 14:10
Show Gist options
  • Save SenpaiSilver/434385c509cfbb70cf04 to your computer and use it in GitHub Desktop.
Save SenpaiSilver/434385c509cfbb70cf04 to your computer and use it in GitHub Desktop.
<?php
/*
** SenpaiSilver
**
** https://gist.github.com/SenpaiSilver
*/
define("SQL_USR", "root");
define("SQL_PSSWD", "");
define("SQL_DB", "test");
define("SQL_HOST", "localhost");
define("SQL_MOD", PDO::FETCH_ASSOC);
class SQL
{
private $_SQL;
private $_LAST;
private $_QUERYTIME;
public function __construct(
$user = SQL_USR, $password = SQL_PSSWD,
$database = SQL_DB, $host = SQL_HOST,
$args = array())
{
$this->_LAST = NULL;
$this->_QUERYTIME = -1;
if ($user == "root")
error_log("You shouldn't use 'root' to connect to your DB.");
try
{
$this->_SQL = new PDO('mysql:host=' .$host. ';dbname=' .$database, $user, $password, $args);
}
catch(Exception $e)
{
die($e->getMessage());
}
}
public function __destruct()
{
$this->_SQL = NULL;
}
//True when executed
//False when failed
public function Execute($query, $data = array())
{
$this->_QUERYTIME = microtime(true);
$qry = $this->_SQL->prepare($query);
$ret = $qry->execute($data);
$this->_QUERYTIME = microtime(true) - $this->_QUERYTIME;
return ($ret);
}
//Returns NULL when failed
public function Fetch($query, $data = array(), $mod = SQL_MOD)
{
$this->_QUERYTIME = microtime(true);
$qry = $this->_SQL->prepare($query);
$qry->execute($data);
$this->_LAST = $qry->fetchAll($mod);
$ret = empty($this->_LAST) ? NULL : $this->_LAST;
$this->_QUERYTIME = microtime(true) - $this->_QUERYTIME;
return ($ret);
}
// Debug purpose
public function DPrintLast()
{
echo("<pre>" .json_encode($this->_LAST == NULL ? "Nothing was fetched." : $this->_LAST, JSON_PRETTY_PRINT). "</pre>");
}
public function DQueryTime($r = 2)
{
return (round($this->_QUERYTIME * 1000, $r));
}
//Prefix tables with $str
public static function PrefixQuery($str)
{
$words = array("INNER", "LEFT", "RIGHT", "JOIN", "ON");
$i = -1;
$flag = 0;
$tmp = "";
if (SQL_PREFIXE == "")
return ($str);
$str = str_replace(',', ', ', $str);
$rray = explode(' ', $str);
$size = count($rray);
while (++$i < $size)
{
while ($rray[$i] == "")
++$i;
if ($rray[$i] == "WHERE")
$flag = 2;
if ($i != 0)
$tmp .= ' ';
if ($flag == 1 && !in_array($rray[$i], $words))
$tmp .= SQL_PREFIXE.$rray[$i];
else
{
if (preg_match('/^[A-Za-z0-9_-]+\.{1}[A-Za-z0-9_-]+$/', $rray[$i]))
$tmp .= SQL_PREFIXE.$rray[$i];
else
$tmp .= $rray[$i];
}
if ($rray[$i] == "FROM")
$flag = 1;
}
return ($tmp);
}
public function Query($q)
{
$query = $this->_SQL->query($q);
return ($query);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment