Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace mint\sys\classes;
- use mysqli;
- use Exception;
- /**
- * @property int insert_id
- */
- class Query
- {
- /** @var \mysqli_result */
- public $handle;
- public function __construct($query)
- {
- $this->handle = $query;
- }
- public function __get($name)
- {
- switch ($name) {
- case 'insert_id':
- return DB::$handle->insert_id;
- default:
- return false;
- }
- }
- /**
- * Выполняет запрос к БД и получает одну запись
- *
- * @return \stdClass|bool
- * @see DB::next()
- */
- public function get()
- {
- if (!$this->handle) return false;
- return $this->handle->fetch_object();
- }
- /**
- * Выполняет запрос к БД и загружает все записи
- *
- * @param callable|null $fn
- * @return array|boolean
- */
- public function getAll($fn = null)
- {
- if ($this->handle) {
- $rows = array();
- while ($row = $this->handle->fetch_object())
- is_callable($fn)
- ? $fn($row)
- : $rows[] = $row;
- return is_callable($fn) ? true : $rows;
- }
- else
- return false;
- }
- }
- class DB
- {
- /**
- * @var mysqli
- */
- static public $handle = false;
- /**
- * @static
- * @param $params array
- * @return bool
- */
- static public function connect($params)
- {
- if (self::$handle = new mysqli('localhost', $params['login'], $params['password']))
- {
- self::$handle->select_db($params['db_name']);
- self::$handle->set_charset('UTF8');
- return true;
- }
- return false;
- }
- /**
- * Возвращает строку в стиле mysql
- *
- * @param string $value
- * @param boolean $q
- * @return string
- */
- public static function str($value, $q = true)
- {
- if ($value === null)
- return 'null';
- else
- return ($q ? '"' : '').self::$handle->real_escape_string($value).($q ? '"' : '');
- }
- public static function sql($query, $args)
- {
- $pattern = '~(\?(?:tbl|t|col|c|set|str|s|int|i|list_int|list|li|l|p)?(?::[a-zA-Z_][a-zA-Z0-9_]*)?)~';
- $array = preg_split($pattern, $query, null, PREG_SPLIT_DELIM_CAPTURE);
- $out = '';
- if (key($args) === 0)
- {
- $mode = 'numeric';
- $anum = count($args);
- $pnum = floor(count($array) / 2);
- if ( $pnum != $anum )
- {
- throw new Exception("Number of args ($anum) doesn't match number of placeholders ($pnum) in [$query]");
- }
- }
- else {
- $mode = 'named';
- }
- static $escape;
- if (!$escape) {
- $escape = array(
- 'tbl' => function($data) {
- return "`$data`";
- },
- 'col' => function($data) {
- return "`$data`";
- },
- 'p' => function($data) {
- return is_null($data) ? '' : $data;
- },
- 'str' => function($data) {
- return is_null($data) ? 'null' : DB::str($data);
- },
- 'int' => function($data) {
- if (is_null($data)) {
- return 'null';
- }
- $data = str_replace(',', '.', $data);
- if (!is_numeric($data)) {
- throw new Exception("Integer (?i) placeholder expects numeric value, ".gettype($data)." given");
- }
- else {
- return number_format($data, 0, '.', ''); // may lose precision on big numbers
- }
- },
- 'set' => function($data) use(&$escape)
- {
- $fv = array();
- foreach ($data as $key=>$value) {
- if ($value === '') $value = '""';
- elseif (is_null($value)) $value = 'null';
- elseif (is_bool($value)) $value = $value ? 1 : 0;
- elseif (is_numeric($value)) $value = number_format($value, 0, '.', '');
- elseif (is_array($value)) {
- $flag = key($value);
- $value = $escape[$flag]($value[$flag]);
- }
- else $value = DB::str($value);
- $fv[] = "`$key`=$value";
- }
- return implode(',', $fv);
- },
- 'list' => function($data) use(&$escape)
- {
- foreach ($data as $key=>$value)
- {
- $data[$key] = $escape['str']($value);
- }
- return implode(',', $data);
- },
- 'list_int' => function($data) use(&$escape)
- {
- foreach ($data as $key=>$value)
- {
- $data[$key] = $escape['int']($value);
- }
- return implode(',', $data);
- },
- );
- $escape['t'] = $escape['tbl'];
- $escape['c'] = $escape['col'];
- $escape['s'] = $escape['str'];
- $escape['i'] = $escape['int'];
- $escape['l'] = $escape['list'];
- $escape['li'] = $escape['list_int'];
- }
- foreach ($array as $i => $part)
- {
- if ( ($i % 2) == 0 )
- {
- $out .= $part;
- continue;
- }
- if ($mode === 'numeric')
- {
- $type = $part;
- $value = array_shift($args);
- }
- else
- {
- list($type, $key) = explode(':', $part);
- if (array_key_exists($key, $args))
- {
- $value = $args[$key];
- }
- else {
- throw new Exception("No key found for the named placeholder [$key] in the data array");
- }
- }
- $type = trim($type, '?');
- $out .= $escape[$type ? : 'str']($value);
- }
- return $out;
- }
- /**
- * Выполняет запрос к БД.
- *
- * @param string $sql
- * @param array|null $args
- * @return bool|Query
- */
- public static function query($sql, $args = null)
- {
- if ($args) {
- $sql = self::sql($sql, $args);
- }
- if ($query = self::$handle->query($sql))
- {
- $query = new Query($query);
- }
- else {
- trigger_error(self::$handle->error, E_USER_WARNING);
- }
- return $query;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement