├── .travis.yml ├── .gitignore ├── tests ├── DeleteTest.php ├── UpdateTest.php ├── InsertTest.php ├── SelectTest.php └── JoinTest.php ├── composer.json ├── example.php ├── LICENCE.md ├── src ├── Cache.php └── Pdox.php ├── README.md └── DOCS.md /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | php: 3 | - "7.0" 4 | - "5.6" 5 | - "5.5" 6 | - "5.4" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.git 2 | /.DS_Store 3 | /composer.lock 4 | /vendor 5 | /index.php 6 | /.htaccess 7 | /.idea 8 | -------------------------------------------------------------------------------- /tests/DeleteTest.php: -------------------------------------------------------------------------------- 1 | 'localhost', 7 | 'driver' => 'mysql', 8 | 'database' => 'test', 9 | 'username' => 'root', 10 | 'password' => '', 11 | 'charset' => 'utf8', 12 | 'collation' => 'utf8_general_ci', 13 | 'prefix' => '' 14 | ]; 15 | 16 | $db = new \Buki\Pdox($config); 17 | 18 | 19 | $query = $db->table('pages')->where('year', 2014)->where('status', 0)->delete(); 20 | 21 | if($query) 22 | { 23 | echo 'Record(s) deleted!'; 24 | } -------------------------------------------------------------------------------- /tests/UpdateTest.php: -------------------------------------------------------------------------------- 1 | 'localhost', 7 | 'driver' => 'mysql', 8 | 'database' => 'test', 9 | 'username' => 'root', 10 | 'password' => '', 11 | 'charset' => 'utf8', 12 | 'collation' => 'utf8_general_ci', 13 | 'prefix' => '' 14 | ]; 15 | 16 | $db = new \Buki\Pdox($config); 17 | 18 | $data = [ 19 | 'username' => 'new-user-name', 20 | 'password' => md5('new-password'), 21 | 'status' => 1 22 | ]; 23 | 24 | $query = $db->table('users')->where('id', 17)->update($data); 25 | 26 | if($query) 27 | { 28 | echo 'Record updated!'; 29 | } -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "izniburak/pdox", 3 | "type": "library", 4 | "description": "Useful Query Builder, PDO Class for PHP. A simple access to your SQL records.", 5 | "keywords": ["php","pdo","sql","query","builder"], 6 | "homepage": "https://github.com/izniburak/PDOx", 7 | "license": "MIT", 8 | "authors": [ 9 | { 10 | "name": "İzni Burak Demirtaş", 11 | "email": "info@burakdemirtas.org", 12 | "homepage": "http://burakdemirtas.org" 13 | } 14 | ], 15 | "require": { 16 | "php": ">=5.4.0", 17 | "ext-pdo": "*" 18 | }, 19 | "autoload": { 20 | "psr-4": { 21 | "Buki\\": "src" 22 | } 23 | }, 24 | "minimum-stability": "dev" 25 | } 26 | -------------------------------------------------------------------------------- /tests/InsertTest.php: -------------------------------------------------------------------------------- 1 | 'localhost', 7 | 'driver' => 'mysql', 8 | 'database' => 'test', 9 | 'username' => 'root', 10 | 'password' => '', 11 | 'charset' => 'utf8', 12 | 'collation' => 'utf8_general_ci', 13 | 'prefix' => '' 14 | ]; 15 | 16 | $db = new \Buki\Pdox($config); 17 | 18 | $data = [ 19 | 'name' => 'Burak', 20 | 'surname' => 'Demirtaş', 21 | 'age' => '24', 22 | 'country' => 'Turkey', 23 | 'city' => 'Ankara', 24 | 'status' => 1 25 | ]; 26 | 27 | $query = $db->table('users')->insert($data); 28 | 29 | if($query) 30 | { 31 | echo 'Record added!
' . 32 | 'InsertID: ' . $db->insertId(); 33 | } -------------------------------------------------------------------------------- /tests/SelectTest.php: -------------------------------------------------------------------------------- 1 | 'localhost', 7 | 'driver' => 'mysql', 8 | 'database' => 'test', 9 | 'username' => 'root', 10 | 'password' => '', 11 | 'charset' => 'utf8', 12 | 'collation' => 'utf8_general_ci', 13 | 'prefix' => '' 14 | ]; 15 | 16 | $db = new \Buki\Pdox($config); 17 | 18 | $records = $db->table('users') 19 | ->select('name, surname, age') 20 | ->where('age', '>', 18) 21 | ->orderBy('id', 'desc') 22 | ->limit(20) 23 | ->getAll(); 24 | 25 | foreach($records as $record) 26 | { 27 | echo $record->name . '
' . 28 | $record->surname . '
' . 29 | $record->age; 30 | } -------------------------------------------------------------------------------- /tests/JoinTest.php: -------------------------------------------------------------------------------- 1 | 'localhost', 7 | 'driver' => 'mysql', 8 | 'database' => 'test', 9 | 'username' => 'root', 10 | 'password' => '', 11 | 'charset' => 'utf8', 12 | 'collation' => 'utf8_general_ci', 13 | 'prefix' => '' 14 | ]; 15 | 16 | $db = new \Buki\Pdox($config); 17 | 18 | $records = $db->table('authors') 19 | ->select('authors.name, articles.title, articles.slug') 20 | ->join('articles', 'users.id', 'articles.user_id') 21 | ->where('users.status', 1) 22 | ->where('articles.status', 1) 23 | ->orderBy('articles.created_at', 'desc') 24 | ->limit(10) 25 | ->getAll(); 26 | 27 | foreach($records as $record) 28 | { 29 | echo $record->name . '
' . 30 | $record->title . '
' . 31 | $record->slug; 32 | } -------------------------------------------------------------------------------- /example.php: -------------------------------------------------------------------------------- 1 | 6 | * @ Web: http://burakdemirtas.org 7 | * @ URL: https://github.com/izniburak/PDOx 8 | * @ Licence: The MIT License (MIT) - Copyright (c) - http://opensource.org/licenses/MIT 9 | * 10 | */ 11 | 12 | require 'vendor/autoload.php'; 13 | 14 | // database config 15 | $config = [ 16 | 'host' => 'localhost', 17 | 'driver' => 'mysql', 18 | 'database' => 'test', 19 | 'username' => 'root', 20 | 'password' => '', 21 | 'charset' => 'utf8', 22 | 'collation' => 'utf8_general_ci', 23 | 'prefix' => '' 24 | ]; 25 | 26 | // start PDOx 27 | $db = new \Buki\Pdox($config); 28 | 29 | // Select Records 30 | $records = $db->table('pages') 31 | ->where('age', '>', 18) 32 | ->orderBy('id', 'desc') 33 | ->limit(10) 34 | ->getAll(); 35 | 36 | var_dump($records); 37 | -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015, İzni Burak Demirtaş 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Cache.php: -------------------------------------------------------------------------------- 1 | 7 | * @web 8 | * @url 9 | * @license The MIT License (MIT) - 10 | */ 11 | 12 | namespace Buki; 13 | 14 | class Cache 15 | { 16 | protected $cacheDir = null; 17 | protected $cache = null; 18 | protected $finish = null; 19 | 20 | function __construct($dir = null, $time = 0) 21 | { 22 | if (! file_exists($dir)) { 23 | mkdir($dir, 0755); 24 | } 25 | 26 | $this->cacheDir = $dir; 27 | $this->cache = $time; 28 | $this->finish = time() + $time; 29 | } 30 | 31 | public function setCache($sql, $result) 32 | { 33 | if (is_null($this->cache)) { 34 | return false; 35 | } 36 | 37 | $cacheFile = $this->cacheDir . $this->fileName($sql) . '.cache'; 38 | $cacheFile = fopen($cacheFile, 'w'); 39 | 40 | if ($cacheFile) { 41 | fputs($cacheFile, json_encode(['data' => $result, 'finish' => $this->finish])); 42 | } 43 | 44 | return; 45 | } 46 | 47 | public function getCache($sql, $array = false) 48 | { 49 | if (is_null($this->cache)) { 50 | return false; 51 | } 52 | 53 | $cacheFile = $this->cacheDir . $this->fileName($sql) . '.cache'; 54 | if (file_exists($cacheFile)) { 55 | $cache = json_decode(file_get_contents($cacheFile), $array); 56 | 57 | if (($array ? $cache['finish'] : $cache->finish) < time()) { 58 | unlink($cacheFile); 59 | return; 60 | } 61 | 62 | return ($array ? $cache['data'] : $cache->data); 63 | } 64 | 65 | return false; 66 | } 67 | 68 | protected function fileName($name) 69 | { 70 | return md5($name); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## PDOx 2 | ``` 3 | _____ _____ ____ 4 | | __ \| __ \ / __ \ 5 | | |__) | | | | | | |_ __ 6 | | ___/| | | | | | \ \/ / 7 | | | | |__| | |__| |> < 8 | |_| |_____/ \____//_/\_\ 9 | ``` 10 | Fast, efficient and useful Query Builder and PDO Class for #PHP 11 | 12 | [![Total Downloads](https://poser.pugx.org/izniburak/pdox/d/total.svg)](https://packagist.org/packages/izniburak/pdox) 13 | [![Latest Stable Version](https://poser.pugx.org/izniburak/pdox/v/stable.svg)](https://packagist.org/packages/izniburak/pdox) 14 | [![Latest Unstable Version](https://poser.pugx.org/izniburak/pdox/v/unstable.svg)](https://packagist.org/packages/izniburak/pdox) 15 | [![License](https://poser.pugx.org/izniburak/pdox/license.svg)](https://packagist.org/packages/izniburak/pdox) 16 | 17 | ## Install 18 | 19 | composer.json file: 20 | ```json 21 | { 22 | "require": { 23 | "izniburak/pdox": "^1" 24 | } 25 | } 26 | ``` 27 | after run the install command. 28 | ``` 29 | $ composer install 30 | ``` 31 | 32 | OR run the following command directly. 33 | 34 | ``` 35 | $ composer require izniburak/pdox 36 | ``` 37 | 38 | ## Example Usage 39 | ```php 40 | require 'vendor/autoload.php'; 41 | 42 | $config = [ 43 | 'host' => 'localhost', 44 | 'driver' => 'mysql', 45 | 'database' => 'test', 46 | 'username' => 'root', 47 | 'password' => '', 48 | 'charset' => 'utf8', 49 | 'collation' => 'utf8_general_ci', 50 | 'prefix' => '' 51 | ]; 52 | 53 | $db = new \Buki\Pdox($config); 54 | 55 | $records = $db->table('users') 56 | ->select('id, name, surname, age') 57 | ->where('age', '>', 18) 58 | ->orderBy('id', 'desc') 59 | ->limit(20) 60 | ->getAll(); 61 | 62 | var_dump($records); 63 | ``` 64 | 65 | ## Docs 66 | Documentation page: [PDOx Docs][doc-url] 67 | 68 | ## Support 69 | [izniburak's homepage][author-url] 70 | 71 | [izniburak's twitter][twitter-url] 72 | 73 | ## Licence 74 | [MIT Licence][mit-url] 75 | 76 | ## Contributing 77 | 78 | 1. Fork it ( https://github.com/izniburak/pdox/fork ) 79 | 2. Create your feature branch (git checkout -b my-new-feature) 80 | 3. Commit your changes (git commit -am 'Add some feature') 81 | 4. Push to the branch (git push origin my-new-feature) 82 | 5. Create a new Pull Request 83 | 84 | ## Contributors 85 | 86 | - [izniburak](https://github.com/izniburak) İzni Burak Demirtaş - creator, maintainer 87 | 88 | [pdox-img]: http://burakdemirtas.org/uploads/images/20140610210255_pdox_pdo_class_for_php.jpg 89 | [paypal-donate-url]: http://burakdemirtas.org 90 | [mit-url]: http://opensource.org/licenses/MIT 91 | [doc-url]: https://github.com/izniburak/PDOx/blob/master/DOCS.md 92 | [author-url]: http://burakdemirtas.org 93 | [twitter-url]: https://twitter.com/izniburak 94 | -------------------------------------------------------------------------------- /DOCS.md: -------------------------------------------------------------------------------- 1 | # PDOx Documentation 2 | 3 | ## Install 4 | `composer.json` file: 5 | ```json 6 | { 7 | "require": { 8 | "izniburak/pdox": "^1" 9 | } 10 | } 11 | ``` 12 | after run the install command. 13 | ``` 14 | $ composer install 15 | ``` 16 | 17 | OR run the following command directly. 18 | 19 | ``` 20 | $ composer require izniburak/pdox 21 | ``` 22 | 23 | ## Quick Usage 24 | ```php 25 | require 'vendor/autoload.php'; 26 | 27 | $config = [ 28 | 'host' => 'localhost', 29 | 'driver' => 'mysql', 30 | 'database' => 'test', 31 | 'username' => 'root', 32 | 'password' => '', 33 | 'charset' => 'utf8', 34 | 'collation' => 'utf8_general_ci', 35 | 'prefix' => '' 36 | ]; 37 | 38 | $db = new \Buki\Pdox($config); 39 | ``` 40 | 41 | Congratulations! Now, you can use PDOx. 42 | 43 | If you have a problem, you can [contact me][support-url]. 44 | 45 | # Detailed Usage and Methods 46 | 47 | ## config 48 | ```php 49 | $config = [ 50 | # Host name or IP Address (optional) 51 | # hostname:port (for Port Usage. Example: 127.0.0.1:1010) 52 | # default value: localhost 53 | 'host' => 'localhost', 54 | 55 | # Database Driver Type (optional) 56 | # default value: mysql 57 | # values: mysql, pgsql, sqlite, oracle 58 | 'driver' => 'mysql', 59 | 60 | # Database Name (required) 61 | 'database' => 'test', 62 | 63 | # Database User Name (required) 64 | 'username' => 'root', 65 | 66 | # Database User Password (required) 67 | 'password' => '', 68 | 69 | # Database Charset (optional) 70 | # default value: utf8 71 | 'charset' => 'utf8', 72 | 73 | # Database Charset Collation (optional) 74 | # default value: utf8_general_ci 75 | 'collation' => 'utf8_general_ci', 76 | 77 | # Database Prefix (optional) 78 | # default value: null 79 | 'prefix' => '', 80 | 81 | # Cache Directory of the Sql Result (optional) 82 | # default value: __DIR__ . '/cache/' 83 | 'cachedir' => __DIR__ . '/cache/sql/' 84 | ]; 85 | 86 | $db = new \Buki\Pdox($config); 87 | ``` 88 | 89 | ## Contents 90 | 91 | * [select](#select) 92 | * [select functions (min, max, sum, avg, count)](#select-functions-min-max-sum-avg-count) 93 | * [table](#table) 94 | * [get AND getAll](#get-and-getall) 95 | * [join](#join) 96 | * [where](#where) 97 | * [grouped](#grouped) 98 | * [in](#in) 99 | * [between](#between) 100 | * [like](#like) 101 | * [groupBy](#groupby) 102 | * [having](#having) 103 | * [orderBy](#orderby) 104 | * [limit - offset](#limit---offset) 105 | * [pagination](#pagination) 106 | * [insert](#insert) 107 | * [update](#update) 108 | * [delete](#delete) 109 | * [analyze](#analyze) - [check](#check) - [checksum](#checksum) - [optimize](#optimize) - [repair](#repair) 110 | * [query](#query) 111 | * [insertId](#insertid) 112 | * [numRows](#numrows) 113 | * [cache](#cache) 114 | * [transaction](#transaction) - [commit](#transaction) - [rollBack](#transaction) 115 | * [error](#error) 116 | * [queryCount](#querycount) 117 | * [getQuery](#getquery) 118 | 119 | ## Methods 120 | 121 | ### select 122 | ```php 123 | # Usage 1: string parameter 124 | $db->select('title, content')->table('test')->getAll(); 125 | # Output: "SELECT title, content FROM test" 126 | 127 | $db->select('title AS t, content AS c')->table('test')->getAll(); 128 | # Output: "SELECT title AS t, content AS c FROM test" 129 | ``` 130 | ```php 131 | # Usage2: array parameter 132 | $db->select(['title', 'content'])->table('test')->getAll(); 133 | # Output: "SELECT title, content FROM test" 134 | 135 | $db->select(['title AS t', 'content AS c'])->table('test')->getAll(); 136 | # Output: "SELECT title AS t, content AS c FROM test" 137 | ``` 138 | 139 | ### select functions (min, max, sum, avg, count) 140 | ```php 141 | # Usage 1: 142 | $db->table('test')->max('price')->get(); 143 | # Output: "SELECT MAX(price) FROM test" 144 | 145 | # Usage 2: 146 | $db->table('test')->count('id', 'total_row')->get(); 147 | # Output: "SELECT COUNT(id) AS total_row FROM test" 148 | ``` 149 | 150 | ### table 151 | ```php 152 | ### Usage 1: string parameter 153 | $db->table('table'); 154 | # Output: "SELECT * FROM table" 155 | 156 | $db->table('table1, table2'); 157 | # Output: "SELECT * FROM table1, table2" 158 | 159 | $db->table('table1 AS t1, table2 AS t2'); 160 | # Output: "SELECT * FROM table1 AS t1, table2 AS t2" 161 | ``` 162 | ```php 163 | ### Usage 2: array parameter 164 | $db->table(['table1', 'table2']); 165 | # Output: "SELECT * FROM table1, table2" 166 | 167 | $db->table(['table1 AS t1', 'table2 AS t2']); 168 | # Output: "SELECT * FROM table1 AS t1, table2 AS t2" 169 | ``` 170 | 171 | ### get AND getAll 172 | ```php 173 | # get(): return 1 record. 174 | # getAll(): return multiple records. 175 | 176 | $db->table('test')->getAll(); 177 | # Output: "SELECT * FROM test" 178 | 179 | $db->select('username')->table('users')->where('status', 1)->getAll(); 180 | # Output: "SELECT username FROM users WHERE status='1'" 181 | 182 | $db->select('title')->table('pages')->where('id', 17)->get(); 183 | # Output: "SELECT title FROM pages WHERE id='17' LIMIT 1" 184 | ``` 185 | 186 | ### join 187 | ```php 188 | $db->table('test as t')->join('foo as f', 't.id', 'f.t_id')->where('t.status', 1)->getAll(); 189 | # Output: "SELECT * FROM test as t JOIN foo as f ON t.id=f.t_id WHERE t.status='1'" 190 | ``` 191 | You can use this method in 7 ways. These; 192 | - join 193 | - left_join 194 | - right_join 195 | - inner_join 196 | - full_outer_join 197 | - left_outer_join 198 | - right_outer_join 199 | 200 | Examples: 201 | ```php 202 | $db->table('test as t')->leftJoin('foo as f', 't.id', 'f.t_id')->getAll(); 203 | # Output: "SELECT * FROM test as t LEFT JOIN foo as f ON t.id=f.t_id" 204 | ``` 205 | 206 | ```php 207 | $db->table('test as t')->fullOuterJoin('foo as f', 't.id', 'f.t_id')->getAll(); 208 | # Output: "SELECT * FROM test as t FULL OUTER JOIN foo as f ON t.id=f.t_id" 209 | ``` 210 | 211 | ### where 212 | ```php 213 | $where = [ 214 | 'name' => 'Burak', 215 | 'age' => 23, 216 | 'status' => 1 217 | ]; 218 | $db->table('test')->where($where)->get(); 219 | # Output: "SELECT * FROM test WHERE name='Burak' AND age='23' AND status='1' LIMIT 1" 220 | 221 | # OR 222 | 223 | $db->table('test')->where('active', 1)->getAll(); 224 | # Output: "SELECT * FROM test WHERE active='1'" 225 | 226 | # OR 227 | 228 | $db->table('test')->where('age', '>=', 18)->getAll(); 229 | # Output: "SELECT * FROM test WHERE age>='18'" 230 | 231 | # OR 232 | 233 | $db->table('test')->where('age = ? OR age = ?', [18, 20])->getAll(); 234 | # Output: "SELECT * FROM test WHERE age='18' OR age='20'" 235 | ``` 236 | 237 | You can use this method in 4 ways. These; 238 | 239 | - where 240 | - orWhere 241 | - notWhere 242 | - orNotWhere 243 | - whereNull 244 | - whereNotNull 245 | 246 | Example: 247 | ```php 248 | $db->table('test')->where('active', 1)->notWhere('auth', 1)->getAll(); 249 | # Output: "SELECT * FROM test WHERE active = '1' AND NOT auth = '1'" 250 | 251 | # OR 252 | 253 | $db->table('test')->where('age', 20)->orWhere('age', '>', 25)->getAll(); 254 | # Output: "SELECT * FROM test WHERE age = '20' OR age > '25'" 255 | 256 | $db->table('test')->whereNotNull('email')->getAll(); 257 | # Output: "SELECT * FROM test WHERE email IS NOT NULL" 258 | ``` 259 | 260 | ### grouped 261 | ```php 262 | $db->table('users') 263 | ->grouped(function($q) { 264 | $q->where('country', 'TURKEY')->orWhere('country', 'ENGLAND'); 265 | }) 266 | ->where('status', 1) 267 | ->getAll(); 268 | # Ouput: "SELECT * FROM users WHERE (country='TURKEY' OR country='ENGLAND') AND status ='1'" 269 | ``` 270 | 271 | ### in 272 | ```php 273 | $db->table('test')->where('active', 1)->in('id', [1, 2, 3])->getAll(); 274 | # Output: "SELECT * FROM test WHERE active = '1' AND id IN ('1', '2', '3')" 275 | ``` 276 | 277 | You can use this method in 4 ways. These; 278 | 279 | - in 280 | - orIn 281 | - notIn 282 | - orNotIn 283 | 284 | Example: 285 | ```php 286 | $db->table('test')->where('active', 1)->notIn('id', [1, 2, 3])->getAll(); 287 | # Output: "SELECT * FROM test WHERE active = '1' AND id NOT IN ('1', '2', '3')" 288 | 289 | # OR 290 | 291 | $db->table('test')->where('active', 1)->orIn('id', [1, 2, 3])->getAll(); 292 | # Output: "SELECT * FROM test WHERE active = '1' OR id IN ('1', '2', '3')" 293 | ``` 294 | 295 | ### between 296 | ```php 297 | $db->table('test')->where('active', 1)->between('age', 18, 25)->getAll(); 298 | # Output: "SELECT * FROM test WHERE active = '1' AND age BETWEEN '18' AND '25'" 299 | ``` 300 | 301 | You can use this method in 4 ways. These; 302 | 303 | - between 304 | - orBetween 305 | - notBetween 306 | - orNotBetween 307 | 308 | Example: 309 | ```php 310 | $db->table('test')->where('active', 1)->notBetween('age', 18, 25)->getAll(); 311 | # Output: "SELECT * FROM test WHERE active = '1' AND age NOT BETWEEN '18' AND '25'" 312 | 313 | # OR 314 | 315 | $db->table('test')->where('active', 1)->orBetween('age', 18, 25)->getAll(); 316 | # Output: "SELECT * FROM test WHERE active = '1' OR age BETWEEN '18' AND '25'" 317 | ``` 318 | 319 | ### like 320 | ```php 321 | $db->table('test')->like('title', "%php%")->getAll(); 322 | # Output: "SELECT * FROM test WHERE title LIKE '%php%'" 323 | ``` 324 | 325 | You can use this method in 4 ways. These; 326 | 327 | - like 328 | - orLike 329 | - notLike 330 | - orNotLike 331 | 332 | Example: 333 | ```php 334 | $db->table('test')->where('active', 1)->notLike('tags', '%dot-net%')->getAll(); 335 | # Output: "SELECT * FROM test WHERE active = '1' AND tags NOT LIKE '%dot-net%'" 336 | 337 | # OR 338 | 339 | $db->table('test')->like('bio', '%php%')->orLike('bio', '%java%')->getAll(); 340 | # Output: "SELECT * FROM test WHERE bio LIKE '%php%' OR bio LIKE '%java%'" 341 | ``` 342 | 343 | ### groupBy 344 | ```php 345 | # Usage 1: One parameter 346 | $db->table('test')->where('status', 1)->groupBy('cat_id')->getAll(); 347 | # Output: "SELECT * FROM test WHERE status = '1' GROUP BY cat_id" 348 | ``` 349 | 350 | ```php 351 | # Usage 1: Array parameter 352 | $db->table('test')->where('status', 1)->groupBy(['cat_id', 'user_id'])->getAll(); 353 | # Output: "SELECT * FROM test WHERE status = '1' GROUP BY cat_id, user_id" 354 | ``` 355 | 356 | ### having 357 | ```php 358 | $db->table('test')->where('status', 1)->groupBy('city')->having('COUNT(person)', 100)->getAll(); 359 | # Output: "SELECT * FROM test WHERE status='1' GROUP BY city HAVING COUNT(person) > '100'" 360 | 361 | # OR 362 | 363 | $db->table('test')->where('active', 1)->groupBy('department_id')->having('AVG(salary)', '<=', 500)->getAll(); 364 | # Output: "SELECT * FROM test WHERE active='1' GROUP BY department_id HAVING AVG(salary) <= '500'" 365 | 366 | # OR 367 | 368 | $db->table('test')->where('active', 1)->groupBy('department_id')->having('AVG(salary) > ? AND MAX(salary) < ?', [250, 1000])->getAll(); 369 | # Output: "SELECT * FROM test WHERE active='1' GROUP BY department_id HAVING AVG(salary) > '250' AND MAX(salary) < '1000'" 370 | ``` 371 | 372 | ### orderBy 373 | ```php 374 | # Usage 1: One parameter 375 | $db->table('test')->where('status', 1)->orderBy('id')->getAll(); 376 | # Output: "SELECT * FROM test WHERE status='1' ORDER BY id ASC" 377 | 378 | ### OR 379 | 380 | $db->table('test')->where('status', 1)->orderBy('id desc')->getAll(); 381 | # Output: "SELECT * FROM test WHERE status='1' ORDER BY id desc" 382 | ``` 383 | 384 | ```php 385 | # Usage 1: Two parameters 386 | $db->table('test')->where('status', 1)->orderBy('id', 'desc')->getAll(); 387 | # Output: "SELECT * FROM test WHERE status='1' ORDER BY id DESC" 388 | ``` 389 | 390 | ```php 391 | # Usage 3: Rand() 392 | $db->table('test')->where('status', 1)->orderBy('rand()')->limit(10)->getAll(); 393 | # Output: "SELECT * FROM test WHERE status='1' ORDER BY rand() LIMIT 10" 394 | ``` 395 | 396 | ### limit - offset 397 | ```php 398 | # Usage 1: One parameter 399 | $db->table('test')->limit(10)->getAll(); 400 | # Output: "SELECT * FROM test LIMIT 10" 401 | ``` 402 | ```php 403 | # Usage 2: Two parameters 404 | $db->table('test')->limit(10, 20)->getAll(); 405 | # Output: "SELECT * FROM test LIMIT 10, 20" 406 | 407 | # Usage 3: with offset method 408 | $db->table('test')->limit(10)->offset(10)->getAll(); 409 | # Output: "SELECT * FROM test LIMIT 10 OFFSET 10" 410 | ``` 411 | 412 | ### pagination 413 | ```php 414 | # First parameter: Data count of per page 415 | # Second parameter: Active page 416 | 417 | $db->table('test')->pagination(15, 1)->getAll(); 418 | # Output: "SELECT * FROM test LIMIT 15 OFFSET 0" 419 | 420 | $db->table('test')->pagination(15, 2)->getAll(); 421 | # Output: "SELECT * FROM test LIMIT 15 OFFSET 15" 422 | ``` 423 | 424 | ### insert 425 | ```php 426 | $data = [ 427 | 'title' => 'test', 428 | 'content' => 'Lorem ipsum dolor sit amet...', 429 | 'time' => '2017-05-19 19:05:00', 430 | 'status' => 1 431 | ]; 432 | 433 | $db->table('pages')->insert($data); 434 | # Output: "INSERT INTO test (title, content, time, status) VALUES ('test', 'Lorem ipsum dolor sit amet...', '2017-05-19 19:05:00', '1')" 435 | ``` 436 | 437 | ### update 438 | ```php 439 | $data = [ 440 | 'username' => 'izniburak', 441 | 'password' => 'pass', 442 | 'activation' => 1, 443 | 'status' => 1 444 | ]; 445 | 446 | $db->table('users')->where('id', 10)->update($data); 447 | # Output: "UPDATE users SET username='izniburak', password='pass', activation='1', status='1' WHERE id='10'" 448 | ``` 449 | 450 | ### delete 451 | ```php 452 | $db->table('test')->where("id", 17)->delete(); 453 | # Output: "DELETE FROM test WHERE id = '17'" 454 | 455 | # OR 456 | 457 | $db->table('test')->delete(); 458 | # Output: "TRUNCATE TABLE delete" 459 | ``` 460 | 461 | ### transaction 462 | ```php 463 | $db->transaction(); 464 | 465 | $data = [ 466 | 'title' => 'new title', 467 | 'status' => 2 468 | ]; 469 | $db->table('test')->where('id', 10)->update($data); 470 | 471 | $db->commit(); 472 | # OR 473 | $db->rollBack(); 474 | ``` 475 | 476 | ### analyze 477 | ```php 478 | $db->table('users')->analyze(); 479 | # Output: "ANALYZE TABLE users" 480 | ``` 481 | 482 | ### check 483 | ```php 484 | $db->table(['users', 'pages'])->check(); 485 | # Output: "CHECK TABLE users, pages" 486 | ``` 487 | 488 | ### checksum 489 | ```php 490 | $db->table(['users', 'pages'])->checksum(); 491 | # Output: "CHECKSUM TABLE users, pages" 492 | ``` 493 | 494 | ### optimize 495 | ```php 496 | $db->table(['users', 'pages'])->optimize(); 497 | # Output: "OPTIMIZE TABLE users, pages" 498 | ``` 499 | 500 | ### repair 501 | ```php 502 | $db->table(['users', 'pages'])->repair(); 503 | # Output: "REPAIR TABLE users, pages" 504 | ``` 505 | 506 | ### query 507 | ```php 508 | # Usage 1: Select all records 509 | $db->query('SELECT * FROM test WHERE id=? AND status=?', [10, 1])->fetchAll(); 510 | 511 | # Usage 2: Select one record 512 | $db->query('SELECT * FROM test WHERE id=? AND status=?', [10, 1])->fetch(); 513 | 514 | # Usage 3: Other queries like Update, Insert, Delete etc... 515 | $db->query('DELETE FROM test WHERE id=?', [10])->exec(); 516 | ``` 517 | 518 | ### insertId 519 | ```php 520 | $data = [ 521 | 'title' => 'test', 522 | 'content' => 'Lorem ipsum dolor sit amet...', 523 | 'time' => time(), 524 | 'status' => 1 525 | ]; 526 | $db->table('pages')->insert($data); 527 | 528 | var_dump($db->insertId()); 529 | ``` 530 | 531 | ### numRows 532 | ```php 533 | $db->select('id, title')->table('test')->where('status', 1)->orWhere('status', 2)->getAll(); 534 | 535 | var_dump($db->numRows()); 536 | ``` 537 | 538 | ### error 539 | ```php 540 | $db->error(); 541 | ``` 542 | 543 | ### cache 544 | ```php 545 | # Usage: ...->cache($time)->... 546 | $db->table('pages')->where('slug', 'example-page')->cache(60)->get(); 547 | # cache time: 60 seconds 548 | ``` 549 | 550 | ### queryCount 551 | ```php 552 | $db->queryCount(); 553 | # The number of all SQL queries on the page until the end of the beginning. 554 | ``` 555 | 556 | ### getQuery 557 | ```php 558 | $db->getQuery(); 559 | # Last SQL Query. 560 | ``` 561 | 562 | [support-url]: https://github.com/izniburak/PDOx#support 563 | -------------------------------------------------------------------------------- /src/Pdox.php: -------------------------------------------------------------------------------- 1 | 7 | * @web 8 | * @url 9 | * @license The MIT License (MIT) - 10 | */ 11 | 12 | namespace Buki; 13 | 14 | use Closure; 15 | use PDO; 16 | use PDOException; 17 | 18 | class Pdox 19 | { 20 | public $pdo = null; 21 | 22 | protected $select = '*'; 23 | protected $from = null; 24 | protected $where = null; 25 | protected $limit = null; 26 | protected $offset = null; 27 | protected $join = null; 28 | protected $orderBy = null; 29 | protected $groupBy = null; 30 | protected $having = null; 31 | protected $grouped = false; 32 | protected $numRows = 0; 33 | protected $insertId = null; 34 | protected $query = null; 35 | protected $error = null; 36 | protected $result = []; 37 | protected $prefix = null; 38 | protected $op = ['=', '!=', '<', '>', '<=', '>=', '<>']; 39 | protected $cache = null; 40 | protected $cacheDir = null; 41 | protected $queryCount = 0; 42 | protected $debug = true; 43 | protected $transactionCount = 0; 44 | 45 | public function __construct(array $config) 46 | { 47 | $config['driver'] = (isset($config['driver']) ? $config['driver'] : 'mysql'); 48 | $config['host'] = (isset($config['host']) ? $config['host'] : 'localhost'); 49 | $config['charset'] = (isset($config['charset']) ? $config['charset'] : 'utf8'); 50 | $config['collation'] = (isset($config['collation']) ? $config['collation'] : 'utf8_general_ci'); 51 | $config['port'] = (strstr($config['host'], ':') ? explode(':', $config['host'])[1] : ''); 52 | $this->prefix = (isset($config['prefix']) ? $config['prefix'] : ''); 53 | $this->cacheDir = (isset($config['cachedir']) ? $config['cachedir'] : __DIR__ . '/cache/'); 54 | $this->debug = (isset($config['debug']) ? $config['debug'] : true); 55 | 56 | $dsn = ''; 57 | 58 | if ($config['driver'] == 'mysql' || $config['driver'] == '' || $config['driver'] == 'pgsql') { 59 | $dsn = $config['driver'] . ':host=' . $config['host'] . ';' 60 | . (($config['port']) != '' ? 'port=' . $config['port'] . ';' : '') 61 | . 'dbname=' . $config['database']; 62 | } elseif ($config['driver'] == 'sqlite') { 63 | $dsn = 'sqlite:' . $config['database']; 64 | } elseif ($config['driver'] == 'oracle') { 65 | $dsn = 'oci:dbname=' . $config['host'] . '/' . $config['database']; 66 | } 67 | 68 | try { 69 | $this->pdo = new PDO($dsn, $config['username'], $config['password']); 70 | $this->pdo->exec("SET NAMES '" . $config['charset'] . "' COLLATE '" . $config['collation'] . "'"); 71 | $this->pdo->exec("SET CHARACTER SET '" . $config['charset'] . "'"); 72 | $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); 73 | } catch (PDOException $e) { 74 | die('Cannot the connect to Database with PDO. ' . $e->getMessage()); 75 | } 76 | 77 | return $this->pdo; 78 | } 79 | 80 | public function table($table) 81 | { 82 | if (is_array($table)) { 83 | $from = ''; 84 | foreach ($table as $key) { 85 | $from .= $this->prefix . $key . ', '; 86 | } 87 | 88 | $this->from = rtrim($from, ', '); 89 | } else { 90 | if (strpos($table, ',') > 0) { 91 | $tables = explode(',', $table); 92 | foreach ($tables as $key => &$value) { 93 | $value = $this->prefix . ltrim($value); 94 | } 95 | $this->from = implode(', ', $tables); 96 | } else { 97 | $this->from = $this->prefix . $table; 98 | } 99 | } 100 | 101 | return $this; 102 | } 103 | 104 | public function select($fields) 105 | { 106 | $select = (is_array($fields) ? implode(', ', $fields) : $fields); 107 | $this->select = ($this->select == '*' ? $select : $this->select . ', ' . $select); 108 | 109 | return $this; 110 | } 111 | 112 | public function max($field, $name = null) 113 | { 114 | $func = 'MAX(' . $field . ')' . (! is_null($name) ? ' AS ' . $name : ''); 115 | $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func); 116 | 117 | return $this; 118 | } 119 | 120 | public function min($field, $name = null) 121 | { 122 | $func = 'MIN(' . $field . ')' . (! is_null($name) ? ' AS ' . $name : ''); 123 | $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func); 124 | 125 | return $this; 126 | } 127 | 128 | public function sum($field, $name = null) 129 | { 130 | $func = 'SUM(' . $field . ')' . (! is_null($name) ? ' AS ' . $name : ''); 131 | $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func); 132 | 133 | return $this; 134 | } 135 | 136 | public function count($field, $name = null) 137 | { 138 | $func = 'COUNT(' . $field . ')' . (! is_null($name) ? ' AS ' . $name : ''); 139 | $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func); 140 | 141 | return $this; 142 | } 143 | 144 | public function avg($field, $name = null) 145 | { 146 | $func = 'AVG(' . $field . ')' . (! is_null($name) ? ' AS ' . $name : ''); 147 | $this->select = ($this->select == '*' ? $func : $this->select . ', ' . $func); 148 | 149 | return $this; 150 | } 151 | 152 | public function join($table, $field1 = null, $op = null, $field2 = null, $type = '') 153 | { 154 | $on = $field1; 155 | $table = $this->prefix . $table; 156 | 157 | if (! is_null($op)) { 158 | $on = ( !in_array($op, $this->op) ? $field1 . ' = ' . $op : $field1 . ' ' . $op . ' ' . $field2 ); 159 | } 160 | 161 | if (is_null($this->join)) { 162 | $this->join = ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on; 163 | } else { 164 | $this->join = $this->join . ' ' . $type . 'JOIN' . ' ' . $table . ' ON ' . $on; 165 | } 166 | 167 | return $this; 168 | } 169 | 170 | public function innerJoin($table, $field1, $op = '', $field2 = '') 171 | { 172 | $this->join($table, $field1, $op, $field2, 'INNER '); 173 | 174 | return $this; 175 | } 176 | 177 | public function leftJoin($table, $field1, $op = '', $field2 = '') 178 | { 179 | $this->join($table, $field1, $op, $field2, 'LEFT '); 180 | 181 | return $this; 182 | } 183 | 184 | public function rightJoin($table, $field1, $op = '', $field2 = '') 185 | { 186 | $this->join($table, $field1, $op, $field2, 'RIGHT '); 187 | 188 | return $this; 189 | } 190 | 191 | public function fullOuterJoin($table, $field1, $op = '', $field2 = '') 192 | { 193 | $this->join($table, $field1, $op, $field2, 'FULL OUTER '); 194 | 195 | return $this; 196 | } 197 | 198 | public function leftOuterJoin($table, $field1, $op = '', $field2 = '') 199 | { 200 | $this->join($table, $field1, $op, $field2, 'LEFT OUTER '); 201 | 202 | return $this; 203 | } 204 | 205 | public function rightOuterJoin($table, $field1, $op = '', $field2 = '') 206 | { 207 | $this->join($table, $field1, $op, $field2, 'RIGHT OUTER '); 208 | 209 | return $this; 210 | } 211 | 212 | public function where($where, $op = null, $val = null, $type = '', $andOr = 'AND') 213 | { 214 | if (is_array($where) && !empty($where)) { 215 | $_where = []; 216 | foreach ($where as $column => $data) { 217 | $_where[] = $type . $column . '=' . $this->escape($data); 218 | } 219 | $where = implode(' ' . $andOr . ' ', $_where); 220 | } else if (is_null($where) || empty($where)) { 221 | return $this; 222 | } else { 223 | if (is_array($op)) { 224 | $params = explode('?', $where); 225 | $_where = ''; 226 | foreach ($params as $key => $value) { 227 | if (! empty($value)) { 228 | $_where .= $type . $value . (isset($op[$key]) ? $this->escape($op[$key]) : ''); 229 | } 230 | } 231 | $where = $_where; 232 | } elseif (! in_array($op, $this->op) || $op == false) { 233 | $where = $type . $where . ' = ' . $this->escape($op); 234 | } else { 235 | $where = $type . $where . ' ' . $op . ' ' . $this->escape($val); 236 | } 237 | } 238 | 239 | if ($this->grouped) { 240 | $where = '(' . $where; 241 | $this->grouped = false; 242 | } 243 | 244 | if (is_null($this->where)) { 245 | $this->where = $where; 246 | } else { 247 | $this->where = $this->where . ' ' . $andOr . ' ' . $where; 248 | } 249 | 250 | return $this; 251 | } 252 | 253 | public function orWhere($where, $op = null, $val = null) 254 | { 255 | $this->where($where, $op, $val, '', 'OR'); 256 | 257 | return $this; 258 | } 259 | 260 | public function notWhere($where, $op = null, $val = null) 261 | { 262 | $this->where($where, $op, $val, 'NOT ', 'AND'); 263 | 264 | return $this; 265 | } 266 | 267 | public function orNotWhere($where, $op = null, $val = null) 268 | { 269 | $this->where($where, $op, $val, 'NOT ', 'OR'); 270 | 271 | return $this; 272 | } 273 | 274 | public function whereNull($where) 275 | { 276 | $where = $where . ' IS NULL'; 277 | if (is_null($this->where)) { 278 | $this->where = $where; 279 | } else { 280 | $this->where = $this->where . ' ' . 'AND ' . $where; 281 | } 282 | 283 | return $this; 284 | } 285 | 286 | public function whereNotNull($where) 287 | { 288 | $where = $where . ' IS NOT NULL'; 289 | if (is_null($this->where)) { 290 | $this->where = $where; 291 | } else { 292 | $this->where = $this->where . ' ' . 'AND ' . $where; 293 | } 294 | 295 | return $this; 296 | } 297 | 298 | public function grouped(Closure $obj) 299 | { 300 | $this->grouped = true; 301 | call_user_func_array($obj, [$this]); 302 | $this->where .= ')'; 303 | 304 | return $this; 305 | } 306 | 307 | public function in($field, array $keys, $type = '', $andOr = 'AND') 308 | { 309 | if (is_array($keys)) { 310 | $_keys = []; 311 | foreach ($keys as $k => $v) { 312 | $_keys[] = (is_numeric($v) ? $v : $this->escape($v)); 313 | } 314 | $keys = implode(', ', $_keys); 315 | $where = $field . ' ' . $type . 'IN (' . $keys . ')'; 316 | 317 | if ($this->grouped) { 318 | $where = '(' . $where; 319 | $this->grouped = false; 320 | } 321 | 322 | if (is_null($this->where)) { 323 | $this->where = $where; 324 | } else { 325 | $this->where = $this->where . ' ' . $andOr . ' ' . $where; 326 | } 327 | } 328 | 329 | return $this; 330 | } 331 | 332 | public function notIn($field, array $keys) 333 | { 334 | $this->in($field, $keys, 'NOT ', 'AND'); 335 | 336 | return $this; 337 | } 338 | 339 | public function orIn($field, array $keys) 340 | { 341 | $this->in($field, $keys, '', 'OR'); 342 | 343 | return $this; 344 | } 345 | 346 | public function orNotIn($field, array $keys) 347 | { 348 | $this->in($field, $keys, 'NOT ', 'OR'); 349 | 350 | return $this; 351 | } 352 | 353 | public function between($field, $value1, $value2, $type = '', $andOr = 'AND') 354 | { 355 | $where = '(' . $field . ' ' . $type . 'BETWEEN ' . ($this->escape($value1) . ' AND ' . $this->escape($value2)) . ')'; 356 | if ($this->grouped) { 357 | $where = '(' . $where; 358 | $this->grouped = false; 359 | } 360 | 361 | if (is_null($this->where)) { 362 | $this->where = $where; 363 | } else { 364 | $this->where = $this->where . ' ' . $andOr . ' ' . $where; 365 | } 366 | 367 | return $this; 368 | } 369 | 370 | public function notBetween($field, $value1, $value2) 371 | { 372 | $this->between($field, $value1, $value2, 'NOT ', 'AND'); 373 | 374 | return $this; 375 | } 376 | 377 | public function orBetween($field, $value1, $value2) 378 | { 379 | $this->between($field, $value1, $value2, '', 'OR'); 380 | 381 | return $this; 382 | } 383 | 384 | public function orNotBetween($field, $value1, $value2) 385 | { 386 | $this->between($field, $value1, $value2, 'NOT ', 'OR'); 387 | 388 | return $this; 389 | } 390 | 391 | public function like($field, $data, $type = '', $andOr = 'AND') 392 | { 393 | $like = $this->escape($data); 394 | 395 | $where = $field . ' ' . $type . 'LIKE ' . $like; 396 | 397 | if ($this->grouped) { 398 | $where = '(' . $where; 399 | $this->grouped = false; 400 | } 401 | 402 | if (is_null($this->where)) { 403 | $this->where = $where; 404 | } else { 405 | $this->where = $this->where . ' ' . $andOr . ' ' . $where; 406 | } 407 | 408 | return $this; 409 | } 410 | 411 | public function orLike($field, $data) 412 | { 413 | $this->like($field, $data, '', 'OR'); 414 | 415 | return $this; 416 | } 417 | 418 | public function notLike($field, $data) 419 | { 420 | $this->like($field, $data, 'NOT ', 'AND'); 421 | 422 | return $this; 423 | } 424 | 425 | public function orNotLike($field, $data) 426 | { 427 | $this->like($field, $data, 'NOT ', 'OR'); 428 | 429 | return $this; 430 | } 431 | 432 | public function limit($limit, $limitEnd = null) 433 | { 434 | if (! is_null($limitEnd)) { 435 | $this->limit = $limit . ', ' . $limitEnd; 436 | } else { 437 | $this->limit = $limit; 438 | } 439 | 440 | return $this; 441 | } 442 | 443 | public function offset($offset) 444 | { 445 | $this->offset = $offset; 446 | 447 | return $this; 448 | } 449 | 450 | public function pagination($perPage, $page) 451 | { 452 | $this->limit = $perPage; 453 | $this->offset = (($page > 0 ? $page : 1) - 1) * $perPage; 454 | 455 | return $this; 456 | } 457 | 458 | public function orderBy($orderBy, $orderDir = null) 459 | { 460 | if (! is_null($orderDir)) { 461 | $this->orderBy = $orderBy . ' ' . strtoupper($orderDir); 462 | } else { 463 | if (stristr($orderBy, ' ') || $orderBy == 'rand()') { 464 | $this->orderBy = $orderBy; 465 | } else { 466 | $this->orderBy = $orderBy . ' ASC'; 467 | } 468 | } 469 | 470 | return $this; 471 | } 472 | 473 | public function groupBy($groupBy) 474 | { 475 | if (is_array($groupBy)) { 476 | $this->groupBy = implode(', ', $groupBy); 477 | } else { 478 | $this->groupBy = $groupBy; 479 | } 480 | 481 | return $this; 482 | } 483 | 484 | public function having($field, $op = null, $val = null) 485 | { 486 | if (is_array($op)) { 487 | $fields = explode('?', $field); 488 | $where = ''; 489 | foreach ($fields as $key => $value) { 490 | if (! empty($value)) { 491 | $where .= $value . (isset($op[$key]) ? $this->escape($op[$key]) : ''); 492 | } 493 | } 494 | $this->having = $where; 495 | } elseif (! in_array($op, $this->op)) { 496 | $this->having = $field . ' > ' . $this->escape($op); 497 | } else { 498 | $this->having = $field . ' ' . $op . ' ' . $this->escape($val); 499 | } 500 | 501 | return $this; 502 | } 503 | 504 | public function numRows() 505 | { 506 | return $this->numRows; 507 | } 508 | 509 | public function insertId() 510 | { 511 | return $this->insertId; 512 | } 513 | 514 | public function error() 515 | { 516 | $msg = '

Database Error

'; 517 | $msg .= '

Query: "' . $this->query . '"

'; 518 | $msg .= '

Error: ' . $this->error . '

'; 519 | 520 | if ($this->debug === true) { 521 | die($msg); 522 | } 523 | 524 | throw new PDOException($this->error . '. (' . $this->query . ')'); 525 | } 526 | 527 | public function get($type = false) 528 | { 529 | $this->limit = 1; 530 | $query = $this->getAll(true); 531 | 532 | if ($type === true) { 533 | return $query; 534 | } 535 | 536 | return $this->query($query, false, (($type == 'array') ? true : false)); 537 | } 538 | 539 | public function getAll($type = false) 540 | { 541 | $query = 'SELECT ' . $this->select . ' FROM ' . $this->from; 542 | 543 | if (! is_null($this->join)) { 544 | $query .= $this->join; 545 | } 546 | 547 | if (! is_null($this->where)) { 548 | $query .= ' WHERE ' . $this->where; 549 | } 550 | 551 | if (! is_null($this->groupBy)) { 552 | $query .= ' GROUP BY ' . $this->groupBy; 553 | } 554 | 555 | if (! is_null($this->having)) { 556 | $query .= ' HAVING ' . $this->having; 557 | } 558 | 559 | if (! is_null($this->orderBy)) { 560 | $query .= ' ORDER BY ' . $this->orderBy; 561 | } 562 | 563 | if (! is_null($this->limit)) { 564 | $query .= ' LIMIT ' . $this->limit; 565 | } 566 | 567 | if (! is_null($this->offset)) { 568 | $query .= ' OFFSET ' . $this->offset; 569 | } 570 | 571 | if ($type === true) { 572 | return $query; 573 | } 574 | 575 | return $this->query($query, true, (($type === 'array') ? true : false)); 576 | } 577 | 578 | public function insert(array $data, $type = false) 579 | { 580 | $query = 'INSERT INTO ' . $this->from; 581 | 582 | $values = array_values($data); 583 | if (isset($values[0]) && is_array($values[0])) { 584 | $column = implode(', ', array_keys($values[0])); 585 | $query .= ' (' . $column . ') VALUES '; 586 | foreach ($values as $value) { 587 | $val = implode(', ', array_map([$this, 'escape'], $value)); 588 | $query .= '(' . $val . '), '; 589 | } 590 | $query = trim($query, ', '); 591 | } else { 592 | $column = implode(', ', array_keys($data)); 593 | $val = implode(', ', array_map([$this, 'escape'], $data)); 594 | $query .= ' (' . $column . ') VALUES (' . $val . ')'; 595 | } 596 | 597 | if ($type === true) { 598 | return $query; 599 | } 600 | 601 | $query = $this->query($query, false); 602 | if ($query) { 603 | $this->insertId = $this->pdo->lastInsertId(); 604 | return $this->insertId(); 605 | } 606 | 607 | return false; 608 | } 609 | 610 | public function update(array $data, $type = false) 611 | { 612 | $query = 'UPDATE ' . $this->from . ' SET '; 613 | $values = []; 614 | 615 | foreach ($data as $column => $val) { 616 | $values[] = $column . '=' . $this->escape($val); 617 | } 618 | $query .= implode(',', $values); 619 | 620 | if (! is_null($this->where)) { 621 | $query .= ' WHERE ' . $this->where; 622 | } 623 | 624 | if (! is_null($this->orderBy)) { 625 | $query .= ' ORDER BY ' . $this->orderBy; 626 | } 627 | 628 | if (! is_null($this->limit)) { 629 | $query .= ' LIMIT ' . $this->limit; 630 | } 631 | 632 | if ($type === true) { 633 | return $query; 634 | } 635 | 636 | return $this->query($query, false); 637 | } 638 | 639 | public function delete($type = false) 640 | { 641 | $query = 'DELETE FROM ' . $this->from; 642 | 643 | if (! is_null($this->where)) { 644 | $query .= ' WHERE ' . $this->where; 645 | } 646 | 647 | if (! is_null($this->orderBy)) { 648 | $query .= ' ORDER BY ' . $this->orderBy; 649 | } 650 | 651 | if (! is_null($this->limit)) { 652 | $query .= ' LIMIT ' . $this->limit; 653 | } 654 | 655 | if ($query == 'DELETE FROM ' . $this->from) { 656 | $query = 'TRUNCATE TABLE ' . $this->from; 657 | } 658 | 659 | if ($type === true) { 660 | return $query; 661 | } 662 | 663 | return $this->query($query, false); 664 | } 665 | 666 | public function analyze() 667 | { 668 | return $this->query('ANALYZE TABLE ' . $this->from, false); 669 | } 670 | 671 | public function check() 672 | { 673 | return $this->query('CHECK TABLE ' . $this->from, false); 674 | } 675 | 676 | public function checksum() 677 | { 678 | return $this->query('CHECKSUM TABLE ' . $this->from, false); 679 | } 680 | 681 | public function optimize() 682 | { 683 | return $this->query('OPTIMIZE TABLE ' . $this->from, false); 684 | } 685 | 686 | public function repair() 687 | { 688 | return $this->query('REPAIR TABLE ' . $this->from, false); 689 | } 690 | 691 | public function transaction() 692 | { 693 | if (! $this->transactionCount++) { 694 | return $this->pdo->beginTransaction(); 695 | } 696 | 697 | $this->pdo->exec('SAVEPOINT trans' . $this->transactionCount); 698 | return $this->transactionCount >= 0; 699 | } 700 | 701 | public function commit() 702 | { 703 | if (! --$this->transactionCount) { 704 | return $this->pdo->commit(); 705 | } 706 | 707 | return $this->transactionCount >= 0; 708 | } 709 | 710 | public function rollBack() 711 | { 712 | if (--$this->transactionCount) { 713 | $this->pdo->exec('ROLLBACK TO trans' . $this->transactionCount + 1); 714 | return true; 715 | } 716 | 717 | return $this->pdo->rollBack(); 718 | } 719 | 720 | public function exec() 721 | { 722 | if (is_null($this->query)) { 723 | return null; 724 | } 725 | 726 | $query = $this->pdo->exec($this->query); 727 | if ($query === false) { 728 | $this->error = $this->pdo->errorInfo()[2]; 729 | return $this->error(); 730 | } 731 | 732 | return $query; 733 | } 734 | 735 | public function fetch($array = false, $all = false) 736 | { 737 | if (is_null($this->query)) { 738 | return null; 739 | } 740 | 741 | $type = ($array === false) ? PDO::FETCH_OBJ : PDO::FETCH_ASSOC; 742 | $query = $this->pdo->query($this->query); 743 | if (! $query) { 744 | $this->error = $this->pdo->errorInfo()[2]; 745 | return $this->error(); 746 | } 747 | 748 | if ($all) { 749 | $result = $query->fetchAll($type); 750 | } else { 751 | $result = $query->fetch($type); 752 | } 753 | 754 | $this->numRows = count($result); 755 | return $result; 756 | } 757 | 758 | public function fetchAll($array = false) 759 | { 760 | return $this->fetch($array, true); 761 | } 762 | 763 | public function query($query, $all = true, $array = false) 764 | { 765 | $this->reset(); 766 | 767 | if (is_array($all) || func_num_args() === 1) { 768 | $params = explode('?', $query); 769 | $newQuery = ''; 770 | foreach ($params as $key => $value) { 771 | if (! empty($value)) { 772 | $newQuery .= $value . (isset($all[$key]) ? $this->escape($all[$key]) : ''); 773 | } 774 | } 775 | 776 | $this->query = $newQuery; 777 | return $this; 778 | } 779 | 780 | $this->query = preg_replace('/\s\s+|\t\t+/', ' ', trim($query)); 781 | $str = false; 782 | foreach (['select', 'optimize', 'check', 'repair', 'checksum', 'analyze'] as $value) { 783 | if (stripos($this->query, $value) === 0) { 784 | $str = true; 785 | break; 786 | } 787 | } 788 | 789 | $cache = false; 790 | if (! is_null($this->cache)) { 791 | $cache = $this->cache->getCache($this->query, $array); 792 | } 793 | 794 | if (! $cache && $str) { 795 | $sql = $this->pdo->query($this->query); 796 | 797 | if ($sql) { 798 | $this->numRows = $sql->rowCount(); 799 | 800 | if (($this->numRows > 0)) { 801 | if ($all) { 802 | $q = []; 803 | 804 | while ($result = ($array == false) ? $sql->fetchAll(PDO::FETCH_OBJ) : $sql->fetchAll(PDO::FETCH_ASSOC)) { 805 | $q[] = $result; 806 | } 807 | 808 | $this->result = $q[0]; 809 | } else { 810 | $q = ($array == false) ? $sql->fetch(PDO::FETCH_OBJ) : $sql->fetch(PDO::FETCH_ASSOC); 811 | $this->result = $q; 812 | } 813 | } 814 | 815 | if (! is_null($this->cache)) { 816 | $this->cache->setCache($this->query, $this->result); 817 | } 818 | $this->cache = null; 819 | } else { 820 | $this->cache = null; 821 | $this->error = $this->pdo->errorInfo()[2]; 822 | 823 | return $this->error(); 824 | } 825 | } elseif ((! $cache && ! $str) || ($cache && ! $str)) { 826 | $this->cache = null; 827 | $this->result = $this->pdo->exec($this->query); 828 | 829 | if ($this->result === false) { 830 | $this->error = $this->pdo->errorInfo()[2]; 831 | 832 | return $this->error(); 833 | } 834 | } else { 835 | $this->cache = null; 836 | $this->result = $cache; 837 | $this->numRows = count($this->result); 838 | } 839 | 840 | $this->queryCount++; 841 | 842 | return $this->result; 843 | } 844 | 845 | public function escape($data) 846 | { 847 | if ($data === null) { 848 | return 'NULL'; 849 | } 850 | 851 | return $this->pdo->quote(trim($data)); 852 | } 853 | 854 | public function cache($time) 855 | { 856 | $this->cache = new Cache($this->cacheDir, $time); 857 | 858 | return $this; 859 | } 860 | 861 | public function queryCount() 862 | { 863 | return $this->queryCount; 864 | } 865 | 866 | public function getQuery() 867 | { 868 | return $this->query; 869 | } 870 | 871 | public function __destruct() 872 | { 873 | $this->pdo = null; 874 | } 875 | 876 | protected function reset() 877 | { 878 | $this->select = '*'; 879 | $this->from = null; 880 | $this->where = null; 881 | $this->limit = null; 882 | $this->offset = null; 883 | $this->orderBy = null; 884 | $this->groupBy = null; 885 | $this->having = null; 886 | $this->join = null; 887 | $this->grouped = false; 888 | $this->numRows = 0; 889 | $this->insertId = null; 890 | $this->query = null; 891 | $this->error = null; 892 | $this->result = []; 893 | $this->transactionCount = 0; 894 | 895 | return; 896 | } 897 | } 898 | --------------------------------------------------------------------------------