├── .gitattributes ├── .gitignore ├── LICENSE.txt ├── README.md ├── classes ├── Config.php └── DB.php ├── core └── init.php ├── functions └── debug.php └── helpers ├── path_helper.php └── uri_helper.php /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | 7 | # Standard to msysgit 8 | *.doc diff=astextplain 9 | *.DOC diff=astextplain 10 | *.docx diff=astextplain 11 | *.DOCX diff=astextplain 12 | *.dot diff=astextplain 13 | *.DOT diff=astextplain 14 | *.pdf diff=astextplain 15 | *.PDF diff=astextplain 16 | *.rtf diff=astextplain 17 | *.RTF diff=astextplain 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows image file caches 2 | Thumbs.db 3 | ehthumbs.db 4 | 5 | # Folder config file 6 | Desktop.ini 7 | 8 | # Recycle Bin used on file shares 9 | $RECYCLE.BIN/ 10 | 11 | # Windows Installer files 12 | *.cab 13 | *.msi 14 | *.msm 15 | *.msp 16 | 17 | # Windows shortcuts 18 | *.lnk 19 | 20 | # ========================= 21 | # Operating System Files 22 | # ========================= 23 | 24 | # OSX 25 | # ========================= 26 | 27 | .DS_Store 28 | .AppleDouble 29 | .LSOverride 30 | .idea 31 | 32 | # Thumbnails 33 | ._* 34 | 35 | # Files that might appear on external disk 36 | .Spotlight-V100 37 | .Trashes 38 | 39 | # Directories potentially created on remote AFP share 40 | .AppleDB 41 | .AppleDesktop 42 | Network Trash Folder 43 | Temporary Items 44 | .apdisk 45 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PHP Custom Query Builder 2 | 3 | This is a custom made simple PHP Query Builder that provides 4 | easy access to functions and make queries easy to understand and execute. 5 | 6 | ## Requirements 7 | 8 | 1. PHP 5.5 or greater 9 | 10 | _Note: for 5.4 or lower support use mysqli instead 11 | 12 | ## Installation 13 | 14 | Download the foldes **core**, **classes**, **functions**, **helpers** into your webserver public_html directory. To test run the file test.php located in the directory. 15 | Make the appropriate configuration settings in the **core/init.php** file so that it can connect to the database and make sure that you set the name of the **public_html** 16 | folder in the config file in both places like this: 17 | 18 | ```php 19 | 'folder' => array( 20 | 'root' => 'root_folder_name', 21 | 22 | 'base_url' => $protocol.'localhost/root_folder_name/', 23 | ``` 24 | 25 | ## Handling The Query Builder 26 | 27 | The **core/init.php** must be required from every file that you create. The classes are autoloaded. 28 | 29 | The DB class is using the Singleton Pattern to avoid multiple unnecessary connections to the database. So you can use the instance very easily like: 30 | 31 | ```php 32 | $db = DB::getInstance(); 33 | $data = $db->get('users'); 34 | 35 | //Will Generate: SELECT * FROM users 36 | ``` 37 | You can also use the builder with custom fields and tables like this: 38 | 39 | ```php 40 | 41 | $data = $db->select('user_id, user_email')->from('users')->fetch(); 42 | //Will Generate: SELECT user_id, user_email FROM users 43 | 44 | $data = $db->select('user_id', 'user_email')->from('users')->fetch(); 45 | //Will Generate: SELECT user_id, user_email FROM users 46 | ``` 47 | All queries are using prepared statements and binding values. You can use where, and, or statements like this: 48 | 49 | 50 | ```php 51 | $data = $db->select('*')->from('users')->where('id', '=', '3')->fetch(); 52 | //Will Generate: SELECT * FROM users WHERE id = 3 and the values will be binded 53 | 54 | $data = $db->select('*')->from('users')->where('id', '=', '3')->and('email', '=', 'myemail@example.com')->fetch(); 55 | //Will Generate: SELECT * FROM users WHERE id = 3 AND email = 'myemail@example.com' and the values will be binded 56 | ``` 57 | 58 | It also supports multiple AND or OR statements like this: 59 | 60 | ```php 61 | $data = $db->select('*') 62 | ->from('users') 63 | ->where('id', '=', '3') 64 | ->and('email', '=', 'myemail@example.com') 65 | ->and('date', '>', '2016-01-01') 66 | ->fetch(); 67 | //Will Generate: SELECT * FROM users WHERE id = ? AND email = ? AND date > ? and the values will be binded 68 | 69 | $data = $db->select('*') 70 | ->from('users') 71 | ->where('id', '=', '3') 72 | ->and('email', '=', 'myemail@example.com') 73 | ->and('date', '>', '2016-01-01') 74 | ->or('date', '<', '2016-08-01') 75 | ->fetch(); 76 | //Will Generate: SELECT * FROM users WHERE id = 3 AND email = 'myemail@example.com' AND date > '2016-01-01' OR date < '2016-08-01' and the values will be binded 77 | ``` 78 | 79 | It also supports BETWEEN, NOT BETWEEN, LIKE, NOT LIKE, IN, NOT IN, REGEXP, NOT REGEXP, IFNULL, IS NULL, IS NOT NULL, HAVING, GROUP BY, ORDER BY, LIMIT statements like this: 80 | 81 | ```php 82 | $data = $db->select('*') 83 | ->from('users') 84 | ->where('id', '=', '3') 85 | ->between('date', '2016-01-01', '2016-08-01') 86 | ->fetch(); 87 | //Will Generate: SELECT * FROM users WHERE id = 3 AND date BETWEEN '2016-01-01' AND '2016-08-01' and the values will be binded 88 | 89 | $data = $db->select('*') 90 | ->from('users') 91 | ->where('id', '=', '3') 92 | ->like('email', 'myemail@example.com') 93 | ->fetch(); 94 | //Will Generate: SELECT * FROM users WHERE id = 3 AND email LIKE '%myemail@example.com%' 95 | 96 | $data = $db->select('*') 97 | ->from('users') 98 | ->where('id', '=', '3') 99 | ->in('postal_code', '000, 111, 222, 333') 100 | ->fetch(); 101 | //Will Generate: SELECT * FROM users WHERE id = 3 AND postal_code IN('000, 111, 222, 333') and the values will be binded 102 | 103 | $data = $db->select('*') 104 | ->from('users') 105 | ->where('id', '=', '3') 106 | ->regex('postal_code', '000|111|222|333') 107 | ->fetch(); 108 | //Will Generate: SELECT * FROM users WHERE id = 3 AND postal_code REGEXP '000|111|222|333' and the values will be binded 109 | 110 | $data = $db->select('*') 111 | ->from('users') 112 | ->where('id', '=', '3') 113 | ->if_null('postal_code', '0') 114 | ->fetch(); 115 | //Will Generate: SELECT * FROM users WHERE id = 3 AND IFNULL(NULL, postal_code = 0) and the values will be binded 116 | 117 | $data = $db->select('*') 118 | ->from('users') 119 | ->where('id', '=', '3') 120 | ->null('address') 121 | ->fetch(); 122 | //Will Generate: SELECT * FROM users WHERE id = 3 AND address IS NULL and the values will be binded 123 | 124 | $data = $db->select('*') 125 | ->from('users') 126 | ->where('id', '=', '3') 127 | ->having('address', '=', 'My Street') 128 | ->fetch(); 129 | //Will Generate: SELECT * FROM users WHERE id = 3 HAVING address = 'My Street' and the values will be binded 130 | 131 | $data = $db->select('*') 132 | ->from('users') 133 | ->where('id', '=', '3') 134 | ->having('address', '=', 'My Street') 135 | ->group('user_id') 136 | ->fetch(); 137 | //Will Generate: SELECT * FROM users WHERE id = 3 HAVING address = 'My Street' GROUP BY user_id and the values will be binded 138 | 139 | $data = $db->select('*') 140 | ->from('users') 141 | ->where('id', '=', '3') 142 | ->having('address', '=', 'My Street') 143 | ->group('user_id') 144 | ->order('email', 'ASC') 145 | ->fetch(); 146 | //Will Generate: SELECT * FROM users WHERE id = 3 HAVING address = 'My Street' GROUP BY user_id ORDER BY email ASC and the values will be binded 147 | 148 | $data = $db->select('*') 149 | ->from('users') 150 | ->where('id', '=', '3') 151 | ->having('address', '=', 'My Street') 152 | ->group('user_id') 153 | ->order('random') 154 | ->fetch(); 155 | //Will Generate: SELECT * FROM users WHERE id = 3 HAVING address = 'My Street' GROUP BY user_id ORDER BY RAND() and the values will be binded 156 | 157 | $data = $db->select('*') 158 | ->from('users') 159 | ->where('id', '=', '3') 160 | ->having('address', '=', 'My Street') 161 | ->group('user_id') 162 | ->order('email', 'ASC') 163 | ->limit(5) 164 | ->fetch(); 165 | //Will Generate: SELECT * FROM users WHERE id = 3 HAVING address = 'My Street' GROUP BY user_id ORDER BY email ASC LIMIT 5,0 and the values will be binded 166 | 167 | 168 | ``` 169 | 170 | The builder also supports JOINS like this: 171 | 172 | 173 | ```php 174 | $data = $db->select('*') 175 | ->from('users') 176 | ->join('orders', 'users.user_id = orders.user', 'INNER') 177 | ->where('user_id', '=', '3') 178 | ->order('user_id', 'ASC') 179 | ->fetch(); 180 | //Will Generate: SELECT * FROM users INNER JOIN orders ON users.user_id = orders.user WHERE user_id = 3 ORDER BY user_id ASC and the values will be binded 181 | 182 | $data = $db->select('*') 183 | ->from('users') 184 | ->join('orders', 'users.user_id = orders.user', 'INNER') 185 | ->join('reviews', 'orders.review_id = reviews.order', 'INNER') 186 | ->where('user_id', '=', '3') 187 | ->order('user_id', 'ASC') 188 | ->fetch(); 189 | //Will Generate: SELECT * FROM users INNER JOIN orders ON users.user_id = orders.user INNER JOIN reviews ON orders.review_id = reviews.order WHERE user_id = 3 ORDER BY user_id ASC and the values will be binded 190 | ``` 191 | The builder also supports UNION like this: 192 | 193 | ```php 194 | $data = $db->union( 195 | $db->select('*')->from('users')->where('user_id', '=', 1)->sql(), 196 | $db->select('*')->from('users')->where('user_id', '=', 2)->sql(), 197 | $db->select('*')->from('users')->where('user_id', '=', 3)->sql() 198 | )->compile(); 199 | //Will generate: SELECT * FROM users WHERE user_id = 1 UNION SELECT * FROM users WHERE user_id = 2 UNION SELECT * FROM users WHERE user_id = 3 200 | ``` 201 | 202 | In the union method you have to use the sql() method to get the sql statement and also the compile() method to execute the query. 203 | 204 | The builder also supports custom binded queries and raw queries like this: 205 | 206 | ```php 207 | //Binded Query 208 | 209 | $data = $db->query("SELECT * FROM users WHERE user_id = ? AND email = ?", array(1, 'myemail@example.com')); 210 | //Will generate: SELECT * FROM users WHERE user_id = 1 AND email = 'myemail@example.com' 211 | 212 | //RAW Query 213 | 214 | $data = $db->raw("SELECT * FROM users WHERE user_id = '1' AND email = 'myemail@example.com' "); 215 | //Will generate: SELECT * FROM users WHERE user_id = 1 AND email = 'myemail@example.com' 216 | 217 | ``` 218 | 219 | The builder also supports insert and update methods like: 220 | 221 | ```php 222 | //Insert 223 | 224 | $data = $db->insert('users', array( 225 | 'name' => 'My name', 226 | 'surname' => 'My Surname', 227 | 'activated' => '0' 228 | )); 229 | 230 | //Update 231 | //Syntax for update method is update($table, $primary_key, $primary_key_value, $items = array()) 232 | 233 | $data = $db->update('users', 'user_id', '3', array( 234 | 'name' => 'My name', 235 | 'surname' => 'My Surname', 236 | 'activated' => '0' 237 | )); 238 | 239 | ``` 240 | You can set custom database charset and names for the connection like this: 241 | 242 | ```php 243 | //Check the charset array in DB.php to see if the charset that you are setting is in the array and allowed. You can 244 | //limit specific charset and names to be set by modifying the array. 245 | $db->setDatabaseCharset('utf8'); 246 | $db->setDatabaseNames('utf8'); 247 | 248 | //and also get the connection data such as 249 | 250 | $db->getDatabaseCharset(); 251 | $db->getDatabaseNames(); 252 | $db->getDns(); 253 | $db->getDatabase(); 254 | $db->getDatabaseDriver(); 255 | $db->getDatabaseHost(); 256 | ``` 257 | 258 | ## Responses 259 | 260 | The returning values from the tables are fetched as Objects and you can print_pre() them like this: 261 | 262 | ```php 263 | print_pre($data->results()); 264 | 265 | //or if you only want the 1st object 266 | 267 | print_pre($data->first()); 268 | ``` 269 | 270 | You can also choose how database should return the results like this: 271 | 272 | 273 | ```php 274 | $db->return_as('object'); 275 | $data = $db->select('*')->from('users')->where('id', '=', '3')->fetch(); 276 | //Will Return as: PDO::FETCH_OBJ 277 | 278 | $db->return_as('array'); 279 | $data = $db->select('*')->from('users')->where('id', '=', '3')->fetch(); 280 | //Will Return as: PDO::FETCH_ASSOC 281 | 282 | $db->return_as('both'); 283 | $data = $db->select('*')->from('users')->where('id', '=', '3')->fetch(); 284 | //Will Return as: PDO::FETCH_BOTH 285 | 286 | $db->return_as('class'); 287 | $data = $db->select('*')->from('users')->where('id', '=', '3')->fetch(); 288 | //Will Return as: PDO::FETCH_CLASS 289 | 290 | ``` 291 | 292 | 293 | ## Pull Requests 294 | 295 | Pull Requests and suggestions are very welcomed!!! 296 | -------------------------------------------------------------------------------- /classes/Config.php: -------------------------------------------------------------------------------- 1 | ', '<', '<=', '>=', '!='); 7 | private $return_type = 'object', $database_name, $database_host, $database_driver, $database_username, $database_charset, $database_names, $_dns, $database_password; 8 | private $_charsets = array('latin1', 'latin2', 'utf8', 'utf8mb4', 'ucs2', 'ascii', 'greek', 'cp866', 'cp852', 'latin7', 'utf16', 'swe7', 'utf32', 'binary',); 9 | 10 | private function __construct() { 11 | $this->database_name = Config::get('mysql/dbname'); 12 | $this->database_host = Config::get('mysql/host'); 13 | $this->database_driver = Config::get('database/driver'); 14 | $this->database_username = Config::get('mysql/username'); 15 | $this->database_password = Config::get('mysql/password'); 16 | $this->database_charset = Config::get('database/charset'); 17 | $this->database_names = Config::get('database/names'); 18 | try { 19 | $this->_dns = '' . $this->database_driver . ':host=' . $this->database_host . ';dbname=' . $this->database_name . ''; 20 | $this->_pdo = new PDO($this->_dns, $this->database_username, $this->database_password); 21 | $this->_pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); 22 | $this->_pdo->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES " . $this->database_names . " "); 23 | $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 24 | $this->_pdo->exec("SET CHARACTER SET '" . $this->database_charset . "'"); 25 | } catch (PDOException $e) { 26 | die($e->getMessage()); 27 | } 28 | } 29 | 30 | public static function getInstance() { 31 | if (!isset(self::$_instance)) { 32 | self::$_instance = new DB(); 33 | } 34 | return self::$_instance; 35 | } 36 | 37 | public function raw($sql, $fetch_type = 'object') { 38 | $this->_query = $this->_pdo->query($sql); 39 | if ($fetch_type === 'both') { 40 | $this->_results = $this->_query->fetchAll(PDO::FETCH_BOTH); 41 | $this->_count = $this->_query->rowCount(); 42 | } elseif ($fetch_type === 'array') { 43 | $this->_results = $this->_query->fetchAll(PDO::FETCH_ASSOC); 44 | $this->_count = $this->_query->rowCount(); 45 | } elseif ($fetch_type === 'class') { 46 | $this->_results = $this->_query->fetchAll(PDO::FETCH_CLASS); 47 | $this->_count = $this->_query->rowCount(); 48 | } elseif ($fetch_type === 'object') { 49 | $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 50 | $this->_count = $this->_query->rowCount(); 51 | } else { 52 | $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 53 | $this->_count = $this->_query->rowCount(); 54 | } 55 | 56 | return $this; 57 | } 58 | 59 | public function join($table, $condition, $type = 'INNER') { 60 | if ($table != '' && !is_null($table)) { 61 | if ($condition != '' && !is_null($condition)) { 62 | $this->_join .= " {$type} JOIN {$table} ON {$condition}"; 63 | } else { 64 | $this->_error = true; 65 | } 66 | } else { 67 | $this->_error = true; 68 | } 69 | return $this; 70 | } 71 | 72 | public function __call($function, $args = array()) { 73 | if ($function === 'and') { 74 | $and = $args; 75 | $field = $and[0]; 76 | $operator = $and[1]; 77 | $value = $and[2]; 78 | if (in_array($operator, $this->_operators)) { 79 | $this->_and .= " AND {$field} {$operator} ?"; 80 | array_push($this->_wherevalues, $value); 81 | } 82 | return $this; 83 | } elseif ($function === 'or') { 84 | $or = $args; 85 | $field = $or[0]; 86 | $operator = $or[1]; 87 | $value = $or[2]; 88 | if (in_array($operator, $this->_operators)) { 89 | $this->_or .= " OR {$field} {$operator} ?"; 90 | array_push($this->_wherevalues, $value); 91 | } 92 | return $this; 93 | } 94 | } 95 | 96 | public function like($column, $value, $or_statement = FALSE) { 97 | if ($this->_where == '') { 98 | $this->_like = " WHERE {$column} LIKE ?"; 99 | $value = '%' . $value . '%'; 100 | array_push($this->_wherevalues, $value); 101 | } elseif ($or_statement === FALSE) { 102 | $this->_like .= " AND {$column} LIKE ?"; 103 | $value = '%' . $value . '%'; 104 | array_push($this->_wherevalues, $value); 105 | } else { 106 | $this->_like .= " OR {$column} LIKE ?"; 107 | $value = '%' . $value . '%'; 108 | array_push($this->_wherevalues, $value); 109 | } 110 | return $this; 111 | } 112 | 113 | public function not_like($column, $value, $or_statement = FALSE) { 114 | if ($this->_where == '') { 115 | $this->_not_like = " WHERE {$column} NOT LIKE ?"; 116 | $value = '%' . $value . '%'; 117 | array_push($this->_wherevalues, $value); 118 | } elseif ($or_statement === FALSE) { 119 | $this->_not_like .= " AND {$column} NOT LIKE ?"; 120 | $value = '%' . $value . '%'; 121 | array_push($this->_wherevalues, $value); 122 | } else { 123 | $this->_not_like .= " OR {$column} NOT LIKE ?"; 124 | $value = '%' . $value . '%'; 125 | array_push($this->_wherevalues, $value); 126 | } 127 | return $this; 128 | } 129 | 130 | public function in($column, $in_array, $or_statement = FALSE) { 131 | $field = $column; 132 | $in = $in_array; 133 | if ($this->_where == '') { 134 | $this->_in = " WHERE {$field} IN({$in})"; 135 | } elseif ($or_statement === FALSE) { 136 | $this->_in .= " AND {$field} IN({$in})"; 137 | } else { 138 | $this->_in .= " OR {$field} IN({$in})"; 139 | } 140 | return $this; 141 | } 142 | 143 | public function not_in($column, $in_array, $or_statement = FALSE) { 144 | $field = $column; 145 | $in = $in_array; 146 | if ($this->_where == '') { 147 | $this->_not_in = " WHERE {$field} NOT IN({$in})"; 148 | } elseif ($or_statement === FALSE) { 149 | $this->_not_in .= " AND {$field} NOT IN({$in})"; 150 | } else { 151 | $this->_not_in .= " OR {$field} NOT IN({$in})"; 152 | } 153 | return $this; 154 | } 155 | 156 | public function regex($column, $value, $or_statement = FALSE) { 157 | if ($this->_where == '') { 158 | $this->_regex = " WHERE {$column} REGEXP ?"; 159 | array_push($this->_wherevalues, $value); 160 | } elseif ($or_statement === FALSE) { 161 | $this->_regex .= " AND {$column} REGEXP ?"; 162 | array_push($this->_wherevalues, $value); 163 | } else { 164 | $this->_regex .= " OR {$column} REGEXP ?"; 165 | array_push($this->_wherevalues, $value); 166 | } 167 | return $this; 168 | } 169 | 170 | public function not_regex($column, $value, $or_statement = FALSE) { 171 | if ($this->_where == '') { 172 | $this->_not_regex = " WHERE {$column} NOT REGEXP ?"; 173 | array_push($this->_wherevalues, $value); 174 | } elseif ($or_statement === FALSE) { 175 | $this->_not_regex .= " AND {$column} NOT REGEXP ?"; 176 | array_push($this->_wherevalues, $value); 177 | } else { 178 | $this->_not_regex .= " OR {$column} NOT REGEXP ?"; 179 | array_push($this->_wherevalues, $value); 180 | } 181 | return $this; 182 | } 183 | 184 | public function null($column, $or_statement = FALSE) { 185 | if ($this->_where == '') { 186 | $this->_null = " WHERE {$column} IS NULL"; 187 | } elseif ($or_statement === FALSE) { 188 | $this->_null .= " AND {$column} IS NULL"; 189 | } else { 190 | $this->_null .= " OR {$column} IS NULL"; 191 | } 192 | return $this; 193 | } 194 | 195 | public function not_null($column, $or_statement = FALSE) { 196 | if ($this->_where == '') { 197 | $this->_not_null = " WHERE {$column} IS NOT NULL"; 198 | } elseif ($or_statement === FALSE) { 199 | $this->_not_null .= " AND {$column} IS NOT NULL"; 200 | } else { 201 | $this->_not_null .= " OR {$column} IS NOT NULL"; 202 | } 203 | return $this; 204 | } 205 | 206 | public function if_null($column, $value, $or_statement = FALSE) { 207 | if ($this->_where == '') { 208 | $this->_if_null = " WHERE IFNULL(NULL, {$column} = ?)"; 209 | array_push($this->_wherevalues, $value); 210 | } elseif ($or_statement === FALSE) { 211 | $this->_if_null .= " AND IFNULL(NULL, {$column} = ?)"; 212 | array_push($this->_wherevalues, $value); 213 | } else { 214 | $this->_if_null .= " OR IFNULL(NULL, {$column} = ?)"; 215 | array_push($this->_wherevalues, $value); 216 | } 217 | return $this; 218 | } 219 | 220 | public function between($column, $value1, $value2) { 221 | if ($this->_where == '') { 222 | $this->_between = " WHERE {$column} BETWEEN ? AND ?"; 223 | array_push($this->_wherevalues, $value1); 224 | array_push($this->_wherevalues, $value2); 225 | } else { 226 | $this->_between .= " AND {$column} BETWEEN ? AND ?"; 227 | array_push($this->_wherevalues, $value1); 228 | array_push($this->_wherevalues, $value2); 229 | } 230 | return $this; 231 | } 232 | 233 | public function not_between($column, $value1, $value2) { 234 | if ($this->_where == '') { 235 | $this->_not_between = " WHERE {$column} NOT BETWEEN ? AND ?"; 236 | array_push($this->_wherevalues, $value1); 237 | array_push($this->_wherevalues, $value2); 238 | } else { 239 | $this->_not_between .= " AND {$column} NOT BETWEEN ? AND ?"; 240 | array_push($this->_wherevalues, $value1); 241 | array_push($this->_wherevalues, $value2); 242 | } 243 | return $this; 244 | } 245 | 246 | public function having($column, $operator, $value) { 247 | if (in_array($operator, $this->_operators)) { 248 | $this->_having .= " HAVING {$column} {$operator} ?"; 249 | array_push($this->_wherevalues, $value); 250 | } 251 | return $this; 252 | } 253 | 254 | public function order($column, $sort = 'ASC') { 255 | if (isset($column)) { 256 | if ($column === 'random') { 257 | $this->_order = " ORDER BY RAND()"; 258 | } else { 259 | $this->_order = " ORDER BY {$column} {$sort}"; 260 | } 261 | } 262 | return $this; 263 | } 264 | 265 | public function group() { 266 | $group = func_get_args(); 267 | if (count($group) > 1) { 268 | $x = 0; 269 | } else { 270 | $x = 1; 271 | } 272 | $values = ''; 273 | foreach ($group as $table) { 274 | $values .= $table; 275 | if ($x < count($table)) { 276 | $values .= ', '; 277 | } 278 | $x++; 279 | } 280 | $this->_group = " GROUP BY {$values}"; 281 | return $this; 282 | } 283 | 284 | public function limit($limit, $offset = 0) { 285 | if (isset($limit)) { 286 | $this->_limit = " LIMIT {$offset}, {$limit}"; 287 | } 288 | return $this; 289 | } 290 | 291 | public function sql() { 292 | $sql = $this->_select . $this->_from . $this->_join . $this->_where . $this->_in . $this->_not_in . $this->_like . $this->_not_like . $this->_regex . $this->_not_regex . $this->_having . $this->_between . $this->_not_between . $this->_null . $this->_not_null . $this->_if_null . $this->_and . $this->_or . $this->_order . $this->_group . $this->_limit; 293 | return $sql; 294 | } 295 | 296 | public function execute() { 297 | $sql = $this->_delete . $this->_from . $this->_where . $this->_in . $this->_not_in . $this->_like . $this->_not_like . $this->_regex . $this->_not_regex . $this->_having . $this->_between . $this->_not_between . $this->_null . $this->_not_null . $this->_if_null . $this->_and . $this->_or . $this->_order . $this->_group . $this->_limit; 298 | // print_pre($sql); 299 | // print_pre($this->_wherevalues); 300 | if (!$this->query($sql, $this->_wherevalues, TRUE)->error()) { 301 | return $this; 302 | } 303 | return false; 304 | } 305 | 306 | public function error() { 307 | return $this->_error; 308 | } 309 | 310 | public function query($sql, $params = array(), $inser_update = FALSE) { 311 | $this->_error = false; 312 | if ($this->_query = $this->_pdo->prepare($sql)) { 313 | $x = 1; 314 | if (count($params)) { 315 | foreach ($params as $param) { 316 | $this->_query->bindValue($x, $param); 317 | $x++; 318 | } 319 | } 320 | $insert_update = ''; 321 | if ($insert_update) { 322 | if (!$this->_query->execute()) { 323 | $this->_error = true; 324 | } 325 | } else { 326 | if ($this->_query->execute()) { 327 | $this->_query->fetchAll($this->getFetchType($this->getReturnType())); 328 | } else { 329 | $this->_error = true; 330 | } 331 | } 332 | } 333 | return $this; 334 | } 335 | 336 | private function getFetchType($return_type) { 337 | if ($return_type === 'both') { 338 | $this->_results = $this->_query->fetchAll(PDO::FETCH_BOTH); 339 | $this->_count = $this->_query->rowCount(); 340 | } elseif ($return_type === 'array') { 341 | $this->_results = $this->_query->fetchAll(PDO::FETCH_ASSOC); 342 | $this->_count = $this->_query->rowCount(); 343 | } elseif ($return_type === 'class') { 344 | $this->_results = $this->_query->fetchAll(PDO::FETCH_CLASS); 345 | $this->_count = $this->_query->rowCount(); 346 | } elseif ($return_type === 'object') { 347 | $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 348 | $this->_count = $this->_query->rowCount(); 349 | } else { 350 | $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 351 | $this->_count = $this->_query->rowCount(); 352 | } 353 | } 354 | 355 | public function getReturnType() { 356 | return $this->return_type; 357 | } 358 | 359 | public function get($table, $where) { 360 | return $this->select('*')->from($table)->where($where)->fetch(); 361 | } 362 | 363 | public function fetch() { 364 | $_sql = $this->_select . $this->_from . $this->_join . $this->_where . $this->_in . $this->_not_in . $this->_like . $this->_not_like . $this->_regex . $this->_not_regex . $this->_having . $this->_between . $this->_not_between . $this->_null . $this->_not_null . $this->_if_null . $this->_and . $this->_or . $this->_order . $this->_group . $this->_limit; 365 | // print_pre($sql); 366 | // print_pre($this->_wherevalues); 367 | if (!$this->query($_sql, $this->_wherevalues)->error()) { 368 | return $this; 369 | } 370 | return false; 371 | } 372 | 373 | public function where() { 374 | $where = func_get_args(); 375 | foreach ($where as $key => $val) { 376 | $field = $where[0]; 377 | $operator = $where[1]; 378 | $value = $where[2]; 379 | if (is_array($val)) { 380 | 381 | $field = $val[0]; 382 | $operator = $val[1]; 383 | $value = $val[2]; 384 | } 385 | } 386 | 387 | 388 | if (in_array($operator, $this->_operators)) { 389 | $this->_where = " WHERE {$field} {$operator} ?"; 390 | $this->_wherevalues[] = $value; 391 | } 392 | return $this; 393 | } 394 | 395 | public function from() { 396 | $from = func_get_args(); 397 | if (count($from) > 1) { 398 | $x = 0; 399 | } else { 400 | $x = 1; 401 | } 402 | $values = ''; 403 | foreach ($from as $table) { 404 | $values .= $table; 405 | if ($x < count($table)) { 406 | $values .= ', '; 407 | } 408 | $x++; 409 | } 410 | $this->_from = "FROM {$values}"; 411 | return $this; 412 | } 413 | 414 | public function select() { 415 | $select_action = func_get_args(); 416 | if (count($select_action) > 1) { 417 | $x = 0; 418 | } else { 419 | $x = 1; 420 | } 421 | $val = ''; 422 | foreach ($select_action as $field) { 423 | $val .= $field; 424 | if ($x < count($field)) { 425 | $val .= ', '; 426 | } 427 | $x++; 428 | } 429 | 430 | $this->_select = "SELECT {$val} "; 431 | return $this; 432 | } 433 | 434 | public function get_all($table) { 435 | return $this->select('*')->from($table)->fetch(); 436 | } 437 | 438 | public function count_all($table) { 439 | return $this->select('COUNT(*) as ' . $table . '_count')->from($table)->fetch(); 440 | } 441 | 442 | public function count_by($table, $where = array()) { 443 | return $this->select('COUNT(*) as ' . $table . '_count')->from($table)->where($where)->fetch(); 444 | } 445 | 446 | public function delete() { 447 | $this->_delete = "DELETE "; 448 | return $this; 449 | } 450 | 451 | public function union() { 452 | $queries = func_get_args(); 453 | $x = 1; 454 | foreach ($queries as $key => $query) { 455 | if ($x < (count($queries))) { 456 | $this->_union .= " UNION " . $queries[$x]; 457 | } 458 | $x++; 459 | } 460 | $this->_union = $queries[0] . $this->_union; 461 | return $this; 462 | } 463 | 464 | public function compile() { 465 | $sql = $this->_union; 466 | if (!$this->query($sql, $this->_wherevalues)->error()) { 467 | return $this; 468 | } 469 | } 470 | 471 | public function insert($table, $fields = array()) { 472 | if (count($fields)) { 473 | $keys = array_keys($fields); 474 | $values = ""; 475 | $x = 1; 476 | foreach ($fields as $field) { 477 | $values .= '?'; 478 | if ($x < count($fields)) { 479 | $values .= ', '; 480 | } 481 | $x++; 482 | } 483 | $sql = "INSERT INTO $table (`" . implode('`, `', $keys) . "`) VALUES ({$values})"; 484 | if (!$this->query($sql, $fields, TRUE)->error()) { 485 | return true; 486 | } 487 | } 488 | return false; 489 | } 490 | 491 | public function update($table, $primary_key, $id, $fields = array()) { 492 | $set = ""; 493 | $x = 1; 494 | foreach ($fields as $name => $value) { 495 | $set .= "{$name} = ?"; 496 | if ($x < count($fields)) { 497 | $set .= ", "; 498 | } 499 | $x++; 500 | } 501 | $sql = "UPDATE {$table} SET {$set} WHERE {$primary_key} = {$id}"; 502 | if (!$this->query($sql, $fields, TRUE)->error()) { 503 | return true; 504 | } 505 | return false; 506 | } 507 | 508 | public function count() { 509 | return $this->_count;; 510 | } 511 | 512 | public function first() { 513 | return $this->results()[0]; 514 | } 515 | 516 | public function results() { 517 | return $this->_results; 518 | } 519 | 520 | public function return_as($return_type = 'object') { 521 | $this->return_type = $return_type; 522 | } 523 | 524 | public function getDatabase() { 525 | return $this->database_name; 526 | } 527 | 528 | public function setDatabase($dbname) { 529 | $this->database_name = $dbname; 530 | } 531 | 532 | public function getDns() { 533 | return $this->_dns; 534 | } 535 | 536 | public function setDns($dns) { 537 | $this->_dns = $dns; 538 | } 539 | 540 | public function getDatabaseHost() { 541 | return $this->database_host; 542 | } 543 | 544 | public function setDatabaseHost($host) { 545 | $this->database_host = $host; 546 | } 547 | 548 | public function getDatabaseDriver() { 549 | return $this->database_driver; 550 | } 551 | 552 | public function setDatabaseDriver($driver) { 553 | $this->database_driver = $driver; 554 | } 555 | 556 | public function getDatabaseNames() { 557 | return $this->database_names; 558 | } 559 | 560 | public function setDatabaseNames($names) { 561 | if (in_array($names, $this->_charsets)) { 562 | $this->database_names = $names; 563 | } 564 | } 565 | 566 | public function getDatabaseCharset() { 567 | return $this->database_charset; 568 | } 569 | 570 | public function setDatabaseCharset($charset) { 571 | if (in_array($charset, $this->_charsets)) { 572 | $this->database_charset = $charset; 573 | } 574 | } 575 | } 576 | 577 | ?> 578 | -------------------------------------------------------------------------------- /core/init.php: -------------------------------------------------------------------------------- 1 | array( 12 | 'host' => 'localhost', 13 | 'username' => 'root', 14 | 'password' => 'root', 15 | 'dbname' => 'database' 16 | ), 17 | 'folder' => array( 18 | 'root' => 'project', 19 | 'logs' => 'logs', 20 | 'classes' => 'classes', 21 | 'functions' => 'functions', 22 | 'helpers' => 'helpers', 23 | ), 24 | 'url' => array( 25 | 'base_url' => $protocol . 'localhost/project/', 26 | 'uri' => ".$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" 27 | ), 28 | 'database' => array( 29 | 'names' => 'utf8mb4', 30 | 'charset' => 'utf8mb4', 31 | 'collation' => 'utf8mb4_general_ci', 32 | 'driver' => 'mysql', 33 | 'character_encoding' => 'UTF-8', 34 | 'charset_html' => 'utf-8' 35 | ) 36 | ); 37 | 38 | spl_autoload_register(function ($class) { 39 | require($_SERVER['DOCUMENT_ROOT'] . $GLOBALS['config']['folder']['root'] . '/' . $GLOBALS['config']['folder']['classes'] . '/' . $class . '.php'); 40 | }); 41 | 42 | require_once($_SERVER['DOCUMENT_ROOT'] . $GLOBALS['config']['folder']['root'] . '/' . $GLOBALS['config']['folder']['functions'] . '/' . 'debug.php'); 43 | require_once($_SERVER['DOCUMENT_ROOT'] . $GLOBALS['config']['folder']['root'] . '/' . $GLOBALS['config']['folder']['helpers'] . '/' . 'uri_helper.php'); 44 | require_once($_SERVER['DOCUMENT_ROOT'] . $GLOBALS['config']['folder']['root'] . '/' . $GLOBALS['config']['folder']['helpers'] . '/' . 'path_helper.php'); 45 | -------------------------------------------------------------------------------- /functions/debug.php: -------------------------------------------------------------------------------- 1 | console.log('" . $flag . ": " . $value . "' );"; 5 | } 6 | 7 | /** 8 | * Writes to the logs/log_(current_date).txt file. 9 | * 10 | * @param String $type the type of the log. 11 | * Posible Types: 12 | * 1) INFO 13 | * 2) DEBUG 14 | * 3) WARNING 15 | * 4) ERROR 16 | * 5) NOTICE 17 | * @param String $message The message we would like to see. 18 | * Every message contains the date and time when the event 19 | * occurred. 20 | * 21 | */ 22 | function log_message($type = 'INFO', $message) { 23 | $filename = "logs_" . date('Y-m-d') . ".txt"; 24 | $textToWrite = $type . " " . date('Y-m-d H:i:s') . " -> " . $message . PHP_EOL; 25 | file_put_contents(log_path() . $filename, $textToWrite, FILE_APPEND); 26 | } 27 | 28 | function print_pre($text) { 29 | echo "
"; 30 | print_r($text); 31 | echo ""; 32 | } -------------------------------------------------------------------------------- /helpers/path_helper.php: -------------------------------------------------------------------------------- 1 |