├── .gitignore ├── db.class.php ├── functions.php ├── import.txt ├── index.php ├── init.php ├── log.txt └── queries.php /.gitignore: -------------------------------------------------------------------------------- 1 | config.php 2 | phpintel/ 3 | .phpintel/ 4 | -------------------------------------------------------------------------------- /db.class.php: -------------------------------------------------------------------------------- 1 | one_row = false; 26 | 27 | $this -> one_field = false; 28 | 29 | $this -> params = []; 30 | 31 | $this -> query = array( 32 | 33 | 'action' => 'SELECT', 34 | 'fields' => '', 35 | 'pre_table' => 'FROM', 36 | 'table' => '', 37 | 'set' => '', 38 | 'join' => '', 39 | 'where' => '', 40 | 'group_by' => '', 41 | 'order_by' => '', 42 | 'limit' => '', 43 | 44 | ); 45 | 46 | $this -> error = false; 47 | 48 | $this -> error_details = []; 49 | 50 | } 51 | 52 | function all($table) { 53 | 54 | return $this -> from($table) -> get(); 55 | 56 | } 57 | 58 | function select($field) { 59 | 60 | $this -> generateQueryPart('fields', $field); 61 | 62 | return $this; 63 | 64 | } 65 | 66 | private function generateQueryPart($field, $field_sql, $field_pre='', $field_sep=', ') { 67 | 68 | if(!empty($field_pre)) 69 | $field_pre .= ' '; 70 | 71 | if(empty($this -> query[$field])) 72 | $this -> query[$field] = $field_pre . $field_sql; 73 | else 74 | $this -> query[$field] .= $field_sep . $field_sql; 75 | 76 | return $this; 77 | 78 | } 79 | 80 | function exists() { 81 | 82 | return $this -> count(); 83 | 84 | } 85 | 86 | function count($field = '') { 87 | 88 | $f = '*'; 89 | 90 | if(!empty($field)) 91 | $f = $field; 92 | 93 | $this -> query['fields'] = ''; 94 | $this -> query['limit'] = ''; 95 | $this -> query['order_by'] = ''; 96 | 97 | return $this -> aggregate("COUNT($f)"); 98 | 99 | } 100 | 101 | function rowsWithCount($field = '') { 102 | 103 | if(!empty($this -> query['fields'])) { 104 | 105 | $query = $this -> getQuery(); 106 | $params = $this -> params; 107 | 108 | $count = $this -> count(); 109 | 110 | $rows = $this -> rows($query, $params); 111 | 112 | return ['rows'=>$rows, 'count'=>$count]; 113 | 114 | } 115 | 116 | } 117 | 118 | function min($field) { 119 | 120 | return $this -> aggregate("MIN({$field})"); 121 | 122 | } 123 | 124 | function max($field) { 125 | 126 | return $this -> aggregate("MAX({$field})"); 127 | 128 | } 129 | 130 | function avg($field) { 131 | 132 | return $this -> aggregate("AVG({$field})"); 133 | 134 | } 135 | 136 | function sum($field) { 137 | 138 | return $this -> aggregate("SUM({$field})"); 139 | 140 | } 141 | 142 | function aggregate($aggregate) { 143 | 144 | $query = $this -> select($aggregate) -> getQuery(); 145 | 146 | if ($aggregate == 'COUNT(*)' && !empty($this -> query['group_by'])) 147 | $query = "SELECT COUNT(*) FROM (".$query.") t"; 148 | 149 | return $this -> value($query, $this -> params); 150 | 151 | } 152 | 153 | function from($from) { 154 | 155 | $this -> query['table'] .= $from; 156 | 157 | return $this; 158 | 159 | } 160 | 161 | function table($table) { 162 | 163 | return $this -> from($table); 164 | 165 | } 166 | 167 | function insert($params) { 168 | 169 | $this -> query['action'] = 'INSERT'; 170 | $this -> query['pre_table'] = 'INTO'; 171 | foreach($params as $key => $value) { 172 | 173 | $set = $key . ' = :' . $key; 174 | 175 | // Add param to params array for prepared statement 176 | $this -> params[$key] = $value; 177 | 178 | $this -> generateQueryPart('set', $set, 'SET'); 179 | 180 | } 181 | 182 | $result = $this -> query($this -> getQuery(), $this -> params); 183 | 184 | return $this -> link -> lastInsertId(); 185 | 186 | } 187 | 188 | function update($params) { 189 | 190 | $this -> query['action'] = 'UPDATE'; 191 | $this -> query['pre_table'] = ''; 192 | 193 | foreach($params as $key => $value) { 194 | 195 | // Add param to params array for prepared statement 196 | $key_unique = $this -> getUniqueKey($key); 197 | $this -> params[$key_unique] = $value; 198 | 199 | $set = $key . ' = :' . $key_unique; 200 | 201 | $this -> generateQueryPart('set', $set, 'SET'); 202 | 203 | } 204 | 205 | $result = $this -> query($this -> getQuery(), $this -> params); 206 | 207 | return $result -> rowCount(); 208 | 209 | } 210 | 211 | private function getUniqueKey($key) { 212 | 213 | $key = str_replace(['.', '(', ')'], ['__', '', ''], $key); 214 | while(array_key_exists($key, $this -> params)) 215 | $key .= '1'; 216 | 217 | return $key; 218 | 219 | } 220 | 221 | function delete() { 222 | 223 | $this -> query['action'] = 'DELETE'; 224 | $this -> query['pre_table'] = 'FROM'; 225 | 226 | $result = $this -> query($this -> getQuery(), $this -> params); 227 | 228 | return $result -> rowCount(); 229 | 230 | } 231 | 232 | function truncate() { 233 | 234 | $this -> query['action'] = 'TRUNCATE'; 235 | $this -> query['pre_table'] = 'TABLE'; 236 | 237 | $result = $this -> query($this -> getQuery(), $this -> params); 238 | 239 | return $result; 240 | 241 | } 242 | 243 | function join($table, $expr1, $expr2) { 244 | 245 | $this -> query['join'] .= 'JOIN ' . $table . " ON $expr1 = $expr2 \n"; 246 | 247 | return $this; 248 | 249 | } 250 | 251 | function leftJoin($table, $expr1, $expr2) { 252 | 253 | return $this -> anyJoin($table, $expr1, $expr2, 'LEFT'); 254 | 255 | } 256 | 257 | function rightJoin($table, $expr1, $expr2) { 258 | 259 | return $this -> anyJoin($table, $expr1, $expr2, 'RIGHT'); 260 | 261 | } 262 | 263 | private function anyJoin($table, $expr1, $expr2, $join_type) { 264 | 265 | $this -> query['join'] .= $join_type . ' JOIN ' . $table . " ON $expr1 = $expr2 \n"; 266 | 267 | return $this; 268 | 269 | } 270 | 271 | function where() { 272 | 273 | $comparison = '='; 274 | $SQL_wpp = $key = $value = ''; 275 | 276 | // Get number of params 277 | $num_args = func_num_args(); 278 | 279 | if ($num_args == 1) 280 | $SQL_wpp = func_get_arg(0); // SQL Without prepared statements 281 | else if($num_args == 2) { 282 | $key = func_get_arg(0); 283 | $value = func_get_arg(1); 284 | } 285 | else if($num_args == 3) { 286 | $key = func_get_arg(0); 287 | $comparison = func_get_arg(1); 288 | $value = func_get_arg(2); 289 | } 290 | 291 | return $this -> wherePart($key, $value, $comparison, ' AND ', $SQL_wpp); 292 | 293 | } 294 | 295 | function whereIn($field, $values){ 296 | 297 | return $this -> where("$field IN ($values)"); 298 | 299 | } 300 | 301 | function whereNotIn($field, $values){ 302 | 303 | return $this -> where("$field NOT IN ($values)"); 304 | 305 | } 306 | 307 | private function wherePart($key, $value, $comparison, $operator, $SQL_wpp = '') { 308 | 309 | if (empty($key) && !empty($SQL_wpp)) { 310 | 311 | $where = $SQL_wpp; 312 | 313 | } else { 314 | 315 | // Add param to params array for prepared statement 316 | $key_unique = $this -> getUniqueKey($key); 317 | $this -> params[$key_unique] = $value; 318 | 319 | $where = $key . ' ' . $comparison . ' ' . ":$key_unique"; 320 | 321 | } 322 | 323 | $this -> generateQueryPart('where', $where, 'WHERE', $operator); 324 | 325 | return $this; 326 | 327 | } 328 | 329 | function orWhere() { 330 | 331 | $comparison = '='; 332 | $key = $value = ''; 333 | 334 | // Get number of params 335 | $num_args = func_num_args(); 336 | 337 | if($num_args == 2) { 338 | $key = func_get_arg(0); 339 | $value = func_get_arg(1); 340 | } 341 | else if($num_args == 3) { 342 | $key = func_get_arg(0); 343 | $comparison = func_get_arg(1); 344 | $value = func_get_arg(2); 345 | } 346 | 347 | return $this -> wherePart($key, $value, $comparison, ' OR '); 348 | 349 | } 350 | 351 | function groupBy($group_by) { 352 | 353 | $this -> generateQueryPart('group_by', $group_by, 'GROUP BY'); 354 | 355 | return $this; 356 | 357 | } 358 | 359 | function orderBy($order_by, $order=1) { 360 | 361 | $order_str = $order == 1 ? 'ASC' : 'DESC'; 362 | 363 | $order_by .= ' ' . $order_str; 364 | 365 | $this -> generateQueryPart('order_by', $order_by, 'ORDER BY'); 366 | 367 | return $this; 368 | 369 | } 370 | 371 | function limit() { 372 | 373 | $skip = $take = 0; 374 | 375 | // Get number of params 376 | $num_args = func_num_args(); 377 | 378 | if($num_args == 1) { 379 | $take = func_get_arg(0); 380 | } 381 | else if($num_args == 2) { 382 | $skip = func_get_arg(0); 383 | $take = func_get_arg(1); 384 | } 385 | 386 | $this -> query['limit'] = "LIMIT $skip, $take"; 387 | 388 | return $this; 389 | 390 | } 391 | 392 | function first($field = '') { 393 | 394 | if($field && strpos($field, ',') === false) 395 | $this -> one_field = true; 396 | else 397 | $this -> one_row = true; 398 | 399 | if($field) 400 | $this -> select($field); 401 | 402 | return $this -> limit(0, 1) -> get(); 403 | 404 | } 405 | 406 | function get($field = '') { 407 | 408 | if($field) 409 | $this -> select($field); 410 | 411 | if(empty($this -> query['fields'])) 412 | $this -> query['fields'] = '*'; 413 | 414 | if($this -> one_field) 415 | $result = $this -> value($this -> getQuery(), $this -> params); 416 | else if($this -> one_row) 417 | $result = $this -> row($this -> getQuery(), $this -> params); 418 | else 419 | $result = $this -> rows($this -> getQuery(), $this -> params); 420 | 421 | return $result; 422 | 423 | } 424 | 425 | function getQuery() { 426 | 427 | return $this -> concatQuery(); 428 | 429 | } 430 | 431 | function concatQuery() { 432 | 433 | return implode(" \n", $this -> query); 434 | 435 | } 436 | 437 | function __construct ($host, $user, $pass, $database) { 438 | 439 | $this -> host = $host; 440 | $this -> user = $user; 441 | $this -> pass = $pass; 442 | $this -> database = $database; 443 | 444 | $this -> connect(); 445 | 446 | // $this -> createErrorsTable(); 447 | 448 | $this -> resetQuery(); 449 | 450 | } 451 | 452 | function connect() { 453 | 454 | try { 455 | 456 | $this -> link = new PDO("mysql:host={$this->host};dbname={$this->database}", $this->user, $this->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")); 457 | 458 | // set the PDO error mode to exception 459 | $this -> link -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 460 | 461 | } 462 | catch(Exception $e) { 463 | 464 | logErrorInFile($e -> getMessage()); 465 | 466 | $this -> registerError(1100); 467 | 468 | } 469 | 470 | return $this -> link; 471 | 472 | } 473 | 474 | public function query($query, $params = null) 475 | { 476 | //p($this -> getQuery()); 477 | $this -> resetQuery(); 478 | 479 | $stmt = $result = null; 480 | 481 | try { 482 | 483 | if(!$this -> error) { 484 | 485 | # create a prepared statement 486 | $stmt = $this -> link -> prepare($query); 487 | 488 | # execute query 489 | if($params) 490 | $result = $stmt -> execute($params); 491 | else 492 | $result = $stmt -> execute(); 493 | 494 | } 495 | 496 | } 497 | catch (Exception $e) { 498 | 499 | $this -> logError($e, $query, $params); 500 | 501 | $this -> registerError(1101); 502 | 503 | } 504 | 505 | return $stmt; 506 | } 507 | 508 | function value($sql, $params = null) { 509 | 510 | $stmt = $this -> query($sql, $params); 511 | 512 | if ($stmt -> rowCount() > 0) { 513 | 514 | $row = $stmt -> fetch(3); //PDO::FETCH_NUM 515 | return $row[0]; 516 | 517 | } 518 | return ''; 519 | 520 | } 521 | 522 | function row($sql, $params = null) { 523 | 524 | $stmt = $this -> query($sql, $params); 525 | 526 | if ($stmt -> rowCount() > 0) { 527 | 528 | $row = $stmt -> fetch(2); 529 | return $row; 530 | 531 | } 532 | return ''; 533 | 534 | } 535 | 536 | function rows($sql, $params = null) { 537 | 538 | $arr = array(); 539 | $stmt = $this -> query($sql, $params); 540 | 541 | if ($stmt -> rowCount() > 0) 542 | $arr = $stmt -> fetchAll(2); 543 | 544 | return $arr; 545 | 546 | } 547 | 548 | function registerError($error_code) { 549 | 550 | $this -> error = true; 551 | $this -> status_code = $error_code; 552 | 553 | } 554 | 555 | function logError($e, $query, $params, $comment = '') { 556 | 557 | try { 558 | 559 | $insert = " INSERT INTO `errors` ( 560 | `query`, 561 | `params`, 562 | `message`, 563 | `code`, 564 | `file`, 565 | `line`, 566 | `trace`, 567 | `comment` 568 | ) 569 | VALUES (?, ?, ?, ?, ?, ?, ?, ?);"; 570 | 571 | $stmt1 = $this -> link -> prepare($insert); 572 | 573 | if($params) 574 | $params = implode('; ', $params); 575 | else 576 | $params = ''; 577 | 578 | $message = $e -> getMessage(); 579 | $code = $e -> getCode(); 580 | $file = $e -> getFile(); 581 | $line = $e -> getLine(); 582 | $trace = $e -> getTraceAsString(); 583 | 584 | $this -> error = true; 585 | $this -> error_details = [$message, $code, $file, $line, $trace]; 586 | 587 | $stmt1 -> execute(array($query, $params, $message, $code, $file, $line, $trace, $comment)); 588 | 589 | } 590 | catch (Exception $ex) { 591 | 592 | logErrorInFile($ex -> getMessage()); 593 | 594 | } 595 | 596 | } 597 | 598 | function createErrorsTable() { 599 | 600 | $exists_query ="SELECT COUNT(table_name) 601 | FROM information_schema.tables 602 | WHERE table_schema = '" . $this -> database . "' 603 | AND table_name = 'errors'"; 604 | 605 | if($this -> value($exists_query) == 0) { 606 | 607 | $queries = array( 608 | 'CREATE TABLE `errors` ( 609 | `id` int(11) NOT NULL, 610 | `query` text NOT NULL, 611 | `params` text NOT NULL, 612 | `message` text NOT NULL, 613 | `code` text NOT NULL, 614 | `file` text NOT NULL, 615 | `line` int(11) NOT NULL, 616 | `trace` text NOT NULL, 617 | `comment` text NOT NULL, 618 | `inserted_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 619 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8;', 620 | 'ALTER TABLE `errors` ADD PRIMARY KEY (`id`);', 621 | 'ALTER TABLE `errors` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;' 622 | ); 623 | 624 | foreach($queries as $query) 625 | $this -> query($query); 626 | 627 | } 628 | 629 | } 630 | 631 | } 632 | -------------------------------------------------------------------------------- /functions.php: -------------------------------------------------------------------------------- 1 | '; 6 | print_r($array); 7 | echo '
'; 8 | 9 | } 10 | 11 | function pe($array){ 12 | 13 | p($array); 14 | exit; 15 | 16 | } 17 | 18 | function logErrorInFile($error_text) { 19 | 20 | $log_file_name = SERVICE_LOG_FILE; 21 | file_put_contents(SERVICE_LOG_FILE, date('Y-m-d H:i:s') . ' ' . $error_text . "\n\n" . file_get_contents(SERVICE_LOG_FILE)); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /import.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tandilashvili/php-mysql-db-query-builder/63afd7001a318013f8d3ffda9dcdf2578ed05e91/import.txt -------------------------------------------------------------------------------- /index.php: -------------------------------------------------------------------------------- 1 | table('word') 10 | // -> select('sentence, comment, id') 11 | -> where('id', '>', 630) 12 | -> orderBy('id') 13 | // -> limit(1) 14 | -> first('sentence, comment, id') ); 15 | 16 | 17 | // Using first('field') function to retrieve only one value. 18 | p( $db -> table('word') 19 | // -> select('sentence, comment, id') 20 | -> where('id', '>', 630) 21 | -> orderBy('id') 22 | // -> limit(1) 23 | -> first('sentence') ); 24 | 25 | 26 | 27 | // Using whereIn and whereNotIn functions 28 | p( $db -> table('word') 29 | -> where("word IN ('oneblah', 'onebluh')") 30 | -> where("word", 'smoothly') 31 | -> whereIn("word", "'blah', 'bluh'") 32 | -> whereNotIn("word", "'smoothly', 'bravely'") 33 | -> where("id", '<', 55) 34 | -> leftJoin('lefttable lt', 'lt.id', 'word.lefttable_id') 35 | -> count()); 36 | 37 | 38 | echo '__'; 39 | 40 | // Using where with only one parameter 41 | p( $db -> table('word') 42 | -> where("word", 'smoothly') 43 | // -> join('jointable jt', 'jt.id', 'word.jointable_id') // commented because there are not such tables to join 44 | // -> rightJoin('blahtable bt', 'bt.id', 'word.blahtable_id') 45 | -> where("word IN ('smoothly', 'bravely')") 46 | -> where("id", '<', 55) 47 | // -> leftJoin('lefttable lt', 'lt.id', 'word.lefttable_id') 48 | -> count()); 49 | 50 | 51 | echo '__'; 52 | 53 | p( $db -> table('word') 54 | -> where("word", 'smoothly') 55 | -> where("word IN ('smoothly', 'bravely')") 56 | -> where("id", '<', 55) 57 | -> count()); 58 | 59 | 60 | echo '__'; 61 | // p( $db -> table('word') 62 | // -> where('word', 'smoothly') 63 | // -> count()); 64 | 65 | // 66 | p( $db -> table('system_variable') 67 | -> select('id, value, name') 68 | -> where('id', '>', '20') 69 | -> limit(7, 10) 70 | -> rowsWithCount()); 71 | 72 | 73 | // get distinct value count 74 | p( $db -> table('system_variable') 75 | -> count('DISTINCT value')); 76 | 77 | 78 | // Get the highest id from the table 79 | p( $db -> table('system_variable') -> max('id')); 80 | 81 | // Get a single field of the first row 82 | p( $db -> table('system_variable') 83 | -> where('id', 32) 84 | -> get('value') 85 | ); 86 | 87 | p( $db -> table('system_variable') -> where('id', '>', '5') -> exists()); 88 | 89 | p( $db -> table('system_variable') -> sum('id')); 90 | 91 | p( $db -> table('system_variable') -> min('id')); 92 | 93 | p( $db -> select('name') -> select('value, id') -> from('system_variable') -> first()); 94 | 95 | // p( $db -> select('id, name') 96 | // -> select('value') 97 | // -> from('system_variable') 98 | // -> where('id', '<', '50') 99 | // -> orderBy('name') 100 | // -> orderBy('id', 2) 101 | // -> limit(5, 5) 102 | // -> get()); 103 | 104 | // Insert a new row into system_variable table 105 | p( $db -> table('system_variable') 106 | -> insert([ 107 | 'value' => '54', 108 | 'name' => '14' 109 | ]) 110 | ); 111 | 112 | //p($db -> table('system_variable') -> where('id', '>', 119) -> delete()); 113 | 114 | //pe($db -> table('system_variable') -> truncate()); 115 | 116 | 117 | pe( $db -> select('value') 118 | -> select('COUNT(id) cnt') 119 | -> from('system_variable') 120 | -> where('id', '<', '190') 121 | -> groupBy('value') 122 | -> get() 123 | ); 124 | 125 | pe( $db -> table('system_variable') 126 | -> where('name', '25') 127 | -> orWhere('id', '>', '113') 128 | -> update(array( 129 | 'value' => 'new-value - 54', 130 | 'name' => '27' 131 | ))); 132 | 133 | pe( $db -> table('word') 134 | -> join('source', 'word.source_id', 'source.id') 135 | -> select('word, sentence, word.comment, source.name') 136 | -> orderBy('word.id') 137 | -> limit(10) 138 | -> get()); 139 | 140 | 141 | p($db -> value(GET_VARIABLE_VALUE, array('id' => 3))); 142 | 143 | 144 | p($db -> row(GET_VARIABLE, array(3))); 145 | 146 | 147 | p($db -> all('errors')); 148 | 149 | 150 | p($db -> rows(GET_VARIABLES, array(3))); 151 | 152 | 153 | p($db -> query(DELETE_VARIABLE, array(58))); 154 | 155 | 156 | p($db -> query(INSERT_VARIABLE, array( 157 | 'value' => 'ის 5', 158 | 'name' => 'ნო 55' 159 | ))); 160 | 161 | 162 | p($db -> query(UPDATE_VARIABLE, array('ი ნომ', 3))); 163 | 164 | 165 | 166 | p($db -> rows(GET_ALL_VARIABLES)); -------------------------------------------------------------------------------- /init.php: -------------------------------------------------------------------------------- 1 |  Unknown database 'dbeng1' 12 | 13 | 2018-12-18 20:35:21 2002 -> php_network_getaddresses: getaddrinfo failed: No such host is known. 14 | 15 | 2018-12-18 20:34:38 1049 -> Unknown database 'dbesng' 16 | 17 | 2018-12-18 20:30:04 1044 -> Access denied for user ''@'localhost' to database 'dbeng' 18 | 19 | 2018-12-18 20:29:17 1045 -> Access denied for user 'root'@'localhost' (using password: YES) 20 | 21 | 2018-12-18 20:28:13 1045 -> Access denied for user 'root'@'localhost' (using password: YES) 22 | 23 | 2018-12-18 19:38:47 Table 'dbeng.errors' doesn't exist 24 | 25 | -------------------------------------------------------------------------------- /queries.php: -------------------------------------------------------------------------------- 1 |