|
| 1 | +<?php |
| 2 | + |
| 3 | +class mysql |
| 4 | +{ |
| 5 | + static $connection = null; |
| 6 | + static $encoding = 'utf8mb4_unicode_ci'; |
| 7 | + static $encoding_ = 'utf8mb4_unicode_ci'; // предыдущая кодировка |
| 8 | + |
| 9 | + static $host = '127.0.0.1'; |
| 10 | + static $user = 'root'; |
| 11 | + static $pass = ''; |
| 12 | + static $base = ''; |
| 13 | + |
| 14 | + static $history = array(); |
| 15 | + static $errors = array(); |
| 16 | + static $error = ''; |
| 17 | + static $cache = false; |
| 18 | + static $cache_sql = array(); |
| 19 | + |
| 20 | + static $data = null; |
| 21 | + static $count = 0; |
| 22 | + |
| 23 | + static function setEncoding($enc) |
| 24 | + { |
| 25 | + self::$encoding_= self::$encoding; |
| 26 | + self::connect(); |
| 27 | + mysqli_set_charset(self::$connection, str_replace('utf-8', 'utf8', self::$encoding = $enc)); |
| 28 | + } |
| 29 | + static function restoreEncoding() |
| 30 | + { |
| 31 | + self::setEncoding(self::$encoding_); |
| 32 | + } |
| 33 | + |
| 34 | + |
| 35 | + static function connect() |
| 36 | + { |
| 37 | + if (self::$connection !== null) return true; |
| 38 | + self::$connection = @mysqli_connect(self::$host, self::$user, self::$pass); |
| 39 | + if (!self::$connection) |
| 40 | + return false; |
| 41 | + if (!mysqli_select_db(self::$connection, self::$base)) |
| 42 | + { |
| 43 | + $errno = mysqli_errno(self::$connection); |
| 44 | + if ($errno) array_push(self::$errors, $errno."\n".mysqli_error(self::$connection)); |
| 45 | + return false; |
| 46 | + } |
| 47 | + self::setEncoding(self::$encoding); |
| 48 | + return true; |
| 49 | + } |
| 50 | + static function prepare_callback($x){ // use ($data) { |
| 51 | + $data = $GLOBALS['prepare_data']; |
| 52 | + $ind =&$GLOBALS['prepare_index']; |
| 53 | + if ($x['field']) { $x['key'] = $x['field']; $x['eq'] = true; } |
| 54 | + $name = $x['key']; |
| 55 | + $eq = $x['eq'] ? "`$name` = " : ''; |
| 56 | + |
| 57 | + $value = ''; |
| 58 | + |
| 59 | + if (is_null($data)) $GLOBALS['prepare_skip'] = true; |
| 60 | + else |
| 61 | + if (is_scalar($data)) $value = $data; |
| 62 | + else |
| 63 | + if (is_array($data)) |
| 64 | + { |
| 65 | + if ($name) |
| 66 | + if (isset($data[$name])) $value = $data[$name]; |
| 67 | + else |
| 68 | + $GLOBALS['prepare_skip'] = true; |
| 69 | + else |
| 70 | + if ($x['type'] != 'as' && isset($data[$ind]) && $data[$ind] !== NULL) $value = $data[$ind++]; |
| 71 | + else |
| 72 | + if (empty($name)) $value = $data; |
| 73 | + else |
| 74 | + $GLOBALS['prepare_skip'] = true; |
| 75 | + } |
| 76 | + else |
| 77 | + if ($data instanceOf Model && $x['type'] != 'kv') |
| 78 | + { |
| 79 | + if (is_null($value = $data->$name)) |
| 80 | + $GLOBALS['prepare_skip'] = true; |
| 81 | + } |
| 82 | + |
| 83 | + if ($GLOBALS['prepare_skip']) return ''; |
| 84 | + |
| 85 | + switch($x['type']) |
| 86 | + { |
| 87 | + case 'p': return $eq.$value; |
| 88 | + case 'i': return $eq.(int)$value; |
| 89 | + case 'f': return $eq.(float)$value; |
| 90 | + case 's': |
| 91 | + case 'S': |
| 92 | +// if ($value === '') $GLOBALS['prepare_skip'] = true; |
| 93 | + if ($x['type'] == 'S') { $value = "%$value%"; $eq = str_replace('=', 'LIKE', $eq); } |
| 94 | + return $eq.self::prepareString($value); |
| 95 | + case 'd': return date('"Y-m-d"', is_numeric($value) && $value > 3000 ? $value : strtotime($value)); |
| 96 | + case 'dt': return date('"Y-m-d H:i:s"', is_numeric($value) && $value > 3000 ? $value : strtotime($value)); |
| 97 | + case 'ai': case 'as': |
| 98 | + if (empty($value)) { $GLOBALS['prepare_skip'] = true; return ''; } |
| 99 | + $a = array(); |
| 100 | + if (is_scalar($value)) $value = explode(',', $value); |
| 101 | + foreach ($value as $v) |
| 102 | + if ($x['type'] == 'ai') |
| 103 | + { |
| 104 | + if (is_numeric($v)) $a[] = $v; |
| 105 | + } |
| 106 | + else |
| 107 | + if ($x['type'] == 'as') |
| 108 | + { |
| 109 | + $a[] = self::prepareString($v); |
| 110 | + } |
| 111 | + return str_replace('=', 'IN', $eq).implode(',', $a); |
| 112 | + case 'kv': case 'kvf': |
| 113 | + $st = ''; $glue = ($x['type'] == 'kvf') ? ' AND ' : ', '; |
| 114 | + if ($value instanceOf Model) $value = $value->getData(); |
| 115 | + else |
| 116 | + if ($data instanceOf Model) $value = $data->getData(); |
| 117 | + |
| 118 | + if (is_array($value)) |
| 119 | + foreach ($value as $k => $v) |
| 120 | + { |
| 121 | + $st .= ($st?$glue:''); |
| 122 | + if (is_array($v)) // задан диапазон значений |
| 123 | + { |
| 124 | + if (count($v) == 2 && is_numeric($v[0]) && is_numeric($v[1])) |
| 125 | + $st .= "`$k` >= ".self::prepareString($v[0])." AND `$k` < ".self::prepareString($v[1]); |
| 126 | + else |
| 127 | + $st .= self::prepare("`$k` IN(?as)", $v); |
| 128 | + } |
| 129 | + else |
| 130 | + { |
| 131 | + $st .= strpos($v, '%') !== false && $GLOBALS['prepare_is_select'] ? "`$k` LIKE " : "`$k` = "; |
| 132 | + if (is_bool($v)) $v = $v ? 1 : 0; |
| 133 | + if (strpos($v, '=') === 0) $st .= substr($v, 1); // COMMENT: например '= NOW()' |
| 134 | + else |
| 135 | +// if (is_numeric($v)) $st .= $v; |
| 136 | +// else |
| 137 | + if (is_null($v)) $st .= 'NULL'; |
| 138 | + else $st .= self::prepareString($v); |
| 139 | + } |
| 140 | + } |
| 141 | + if (!$st) $st = 1; |
| 142 | + return $st; |
| 143 | + default: |
| 144 | + return ''; |
| 145 | + } |
| 146 | + } |
| 147 | + static function prepareString($st) |
| 148 | + { |
| 149 | + return '"'.addslashes($st).'"'; |
| 150 | + } |
| 151 | + static function prepare($sql, $data='_stored', $d2='_stored', $d3=NULL, $d4=NULL, $d5=NULL, $d6=NULL) |
| 152 | + { |
| 153 | + $sql = "\n$sql "; |
| 154 | + if ($data === '_stored') $data = self::$data; |
| 155 | + |
| 156 | + if ($d2 !== '_stored') |
| 157 | + $data = array($data, $d2, $d3, $d4, $d5, $d6); |
| 158 | + |
| 159 | + self::$data = $data; |
| 160 | + |
| 161 | + // FIXME: убрать глобальные переменные |
| 162 | + $GLOBALS['prepare_is_select'] = stripos(" $sql", 'SELECT'); |
| 163 | + $GLOBALS['prepare_data'] = $data; |
| 164 | + $GLOBALS['prepare_index'] = 0; |
| 165 | + $GLOBALS['prepare_skip'] = false; |
| 166 | + |
| 167 | + $sql = preg_replace_callback('#((?<field>[a-z0-9_]+)=)?\?(?<type>s|S|i|f|dt|d|p|ai|as|kvf|kv):?(?<key>[a-z0-9_]*)(?<eq>=?)#i', |
| 168 | + 'mysql::prepare_callback', $sql); |
| 169 | + if (@$GLOBALS['prepare_skip']) $sql = ''; |
| 170 | + |
| 171 | + unset($GLOBALS['prepare_is_select']); |
| 172 | + unset($GLOBALS['prepare_data']); |
| 173 | + unset($GLOBALS['prepare_index']); |
| 174 | + unset($GLOBALS['prepare_skip']); |
| 175 | + |
| 176 | + return $sql; |
| 177 | + } |
| 178 | + static function query($sql) |
| 179 | + { |
| 180 | + $t = microtime(true); |
| 181 | + $sql_dump = mb_strlen($sql) > 5*1024 ? mb_substr($sql, 0, 5*1024 - 3).'...' : $sql; |
| 182 | + self::connect(); |
| 183 | + $res = @mysqli_query(self::$connection, $sql); |
| 184 | + $errno = mysqli_errno(self::$connection); |
| 185 | + if ($errno) |
| 186 | + { |
| 187 | + array_push(self::$errors, self::$error = $errno."\n".mysqli_error(self::$connection)."\n".$sql_dump); |
| 188 | + //log::mysql('error', [$sql, self::$error]); |
| 189 | + } |
| 190 | + array_push(self::$history, $sql_dump.' -- '.$t.' + '.round(microtime(true)-$t, 4)); |
| 191 | + return $errno ? false : $res; |
| 192 | + } |
| 193 | + static function fetch($res) |
| 194 | + { |
| 195 | + return mysqli_fetch_assoc($res); |
| 196 | + } |
| 197 | + static function getList($sql) |
| 198 | + { |
| 199 | + $is_sql_count = false; |
| 200 | + if (strpos($sql, 'SELECT') !== false && strpos($sql, 'LIMIT') !== false) |
| 201 | + { |
| 202 | + $sql = preg_replace('/SELECT /', 'SELECT SQL_CALC_FOUND_ROWS ', $sql, 1); |
| 203 | + $is_sql_count = true; |
| 204 | + } |
| 205 | + |
| 206 | + $res = self::query($sql); |
| 207 | + if (!$res) return array(); |
| 208 | + $ret = array(); |
| 209 | + while ($row = mysqli_fetch_assoc($res)) |
| 210 | + $ret[] = $row; |
| 211 | + self::$count = $is_sql_count ? (int)self::getValue('SELECT FOUND_ROWS()') : count($ret); |
| 212 | + return $ret; |
| 213 | + } |
| 214 | + static function getItem($sql) |
| 215 | + { |
| 216 | + if (self::$cache && isset($cache_sql[$sql])) return $cache_sql[$sql]; |
| 217 | + $res = self::query($sql); |
| 218 | + if ($res === false) return array(); |
| 219 | + $res = mysqli_fetch_assoc($res); if (is_null($res)) $res = array(); |
| 220 | + if (self::$cache) $cache_sql[$sql] = $res; |
| 221 | + return $res; |
| 222 | + } |
| 223 | + static function getValue($sql) |
| 224 | + { |
| 225 | + if (self::$cache && isset($cache_sql[$sql])) return $cache_sql[$sql]; |
| 226 | + $res = self::query($sql); |
| 227 | + if (!is_object($res)) return NULL; |
| 228 | + $res = mysqli_fetch_array($res); |
| 229 | + if (empty($res)) return NULL; |
| 230 | + $res = $res[0]; |
| 231 | + if (self::$cache) $cache_sql[$sql] = $res; |
| 232 | + return $res; |
| 233 | + } |
| 234 | + static function getValues($sql, $field = null) |
| 235 | + { |
| 236 | + $res = self::getList($sql); |
| 237 | + if (is_null($field)) $field = array_keys($res[0])[0]; |
| 238 | + foreach ($res as $i => $a) |
| 239 | + $res[$i] = $a[$field]; |
| 240 | + return $res; |
| 241 | + } |
| 242 | + static function getListCount() |
| 243 | + { |
| 244 | + return self::$count; |
| 245 | + } |
| 246 | + static function get($table, $id, $fields = NULL) |
| 247 | + { |
| 248 | + if (empty($fields)) $fields = '*'; |
| 249 | + $p = is_numeric($id) ? '`id` = ?i' : '?p'; |
| 250 | + $sql = mysql::prepare("SELECT $fields FROM `$table` WHERE $p LIMIT 1", $id); |
| 251 | + return mysql::getItem($sql); |
| 252 | + } |
| 253 | + static function search($table, $a, $fields = NULL, $orderBy = NULL) |
| 254 | + { |
| 255 | + if ( empty($fields)) $fields = '*'; |
| 256 | + if (!empty($orderBy)) $orderBy = "ORDER BY $orderBy"; |
| 257 | + $sql = mysql::prepare("SELECT $fields FROM `$table` WHERE ?kvf $orderBy", $a); |
| 258 | + return mysql::getList($sql); |
| 259 | + } |
| 260 | + static function insert($table, $a) |
| 261 | + { |
| 262 | + $sql = self::prepare("INSERT INTO `$table` SET ?kv", $a); |
| 263 | + $res = mysql::query($sql); |
| 264 | + return mysqli_errno(self::$connection) ? false : mysql::getLastInsertId(); |
| 265 | + } |
| 266 | + static function insert_values($table, $a) |
| 267 | + { |
| 268 | + if (empty($a)) return false; |
| 269 | + $values = []; |
| 270 | + foreach ($a as $a) $values[] = mysql::prepare('(?as)', $a); |
| 271 | + $sql = self::prepare("INSERT INTO `$table` VALUES ".implode(',', $values)); |
| 272 | + $res = mysql::query($sql); |
| 273 | + return mysqli_errno(self::$connection) ? false : mysql::getLastInsertId(); |
| 274 | + } |
| 275 | + static function getLastInsertId() { return mysqli_insert_id(self::$connection); } |
| 276 | + static function insert_duplicate($table, $a) |
| 277 | + { |
| 278 | + $sql = self::prepare("INSERT INTO `$table` SET ?kv ON DUPLICATE KEY UPDATE ?kv", $a, $a); |
| 279 | + $res = mysql::query($sql); |
| 280 | + return mysqli_errno(self::$connection) ? false : self::getRowsCount(); |
| 281 | + } |
| 282 | + static function replace($table, $a) |
| 283 | + { |
| 284 | + $sql = self::prepare("REPLACE INTO `$table` SET ?kv", $a); |
| 285 | + $res = mysql::query($sql); |
| 286 | + return mysqli_errno(self::$connection) ? false : true; |
| 287 | + } |
| 288 | + static function update($table, $a, $where = NULL) |
| 289 | + { |
| 290 | + // передали id записи, которую нужно изменить |
| 291 | + if (is_numeric($where)) |
| 292 | + { |
| 293 | + $a['id'] = $where; |
| 294 | + $where = NULL; |
| 295 | + } |
| 296 | + // передали условие выборки записей на изменение |
| 297 | + if (is_null($where)) |
| 298 | + { |
| 299 | + if (empty($a['id'])) return NULL; |
| 300 | + $where = self::prepare("`id` = ?i", $a['id']); |
| 301 | + unset($a['id']); |
| 302 | + } |
| 303 | + // $where в качестве хеша |
| 304 | + if (is_array($where)) |
| 305 | + { |
| 306 | + $where = mysql::prepare('?kvf', $where); |
| 307 | + } |
| 308 | + if (empty($a)) return 0; |
| 309 | + $sql = self::prepare("UPDATE `$table` SET ?kv WHERE ?p", $a, $where); |
| 310 | + $res = self::query($sql); |
| 311 | + if ($res === false) return false; |
| 312 | + return self::getRowsCount(); |
| 313 | + } |
| 314 | + static function delete($table, $sql) |
| 315 | + { |
| 316 | + if (empty($sql)) return false; |
| 317 | + if (is_array($sql)) $sql = mysql::prepare('?kvf', $sql); |
| 318 | + if (is_numeric($sql)) $sql = mysql::prepare("`id` = ?i", $sql); // передали число |
| 319 | + $sql = self::prepare("DELETE FROM `$table` WHERE ?p", $sql); |
| 320 | + return self::query($sql); |
| 321 | + } |
| 322 | + /** кол-во изменённых рядов */ |
| 323 | + static function getRowsCount() |
| 324 | + { |
| 325 | + return mysqli_affected_rows(self::$connection); |
| 326 | + } |
| 327 | + static function getLastError() |
| 328 | + { |
| 329 | + $errno = mysqli_errno(self::$connection); |
| 330 | + return $errno ? array('errno' => $errno) : array(); |
| 331 | + } |
| 332 | + static function setDefault($value, &$a, $fields='') |
| 333 | + { |
| 334 | + $x = $a; |
| 335 | + if (!empty($fields)) $x = array_intersect_key($a, array_fill_keys(explode(',', $fields), 1)); |
| 336 | + foreach ($x as $k => $v) |
| 337 | + { |
| 338 | + if (empty($v)) $a[$k] = $value; |
| 339 | + } |
| 340 | + } |
| 341 | +} |
0 commit comments