Created
March 4, 2018 18:50
-
-
Save vtr0n/c69255861286aaa9fb5065c2c58a9154 to your computer and use it in GitHub Desktop.
MySQL Class Simple
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 | |
class MySQL | |
{ | |
var $link; | |
function __construct() | |
{ | |
include_once dirname(__FILE__) . '/config.php'; | |
$this->link = mysqli_connect( | |
config\MYSQL_HOST, | |
config\MYSQL_USERNAME, | |
config\MYSQL_PASSWORD, | |
config\MYSQL_DB, | |
config\MYSQL_PORT | |
); | |
mysqli_set_charset($this->link, "utf8mb4"); | |
} | |
public function query() | |
{ | |
//var_dump($this->prepareQuery(func_get_args())); | |
return mysqli_query($this->link, $this->prepareQuery(func_get_args())); | |
} | |
/* Security methods */ | |
protected function prepareQuery($args) | |
{ | |
$query = ''; | |
$raw = array_shift($args); | |
$array = preg_split('~(\?[nsiuap])~u', $raw, null, PREG_SPLIT_DELIM_CAPTURE); | |
foreach ($array as $i => $part) { | |
if (($i % 2) == 0) { | |
$query .= $part; | |
continue; | |
} | |
$value = array_shift($args); | |
switch ($part) { | |
case '?i': | |
$part = $this->escapeInt($value); | |
break; | |
case '?s': | |
$part = $this->escapeString($value); | |
break; | |
} | |
$query .= $part; | |
} | |
return $query; | |
} | |
protected function escapeInt($value) | |
{ | |
if ($value === NULL) { | |
return 'NULL'; | |
} | |
if (!is_numeric($value)) { | |
$this->error("Integer (?i) placeholder expects numeric value, " . gettype($value) . " given"); | |
return FALSE; | |
} | |
if (is_float($value)) { | |
$value = number_format($value, 0, '.', ''); | |
} | |
return $value; | |
} | |
protected function escapeString($value) | |
{ | |
if ($value === NULL) { | |
return 'NULL'; | |
} | |
return "'" . mysqli_real_escape_string($this->link, $value) . "'"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment