├── .gitignore ├── README.md ├── composer.json ├── src └── Database.php └── tests └── test.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | /vendor/ 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Updated version can be found here https://github.com/im4aLL/roolith-database 2 | 3 | # PDO MySql driver class for PHP 4 | 5 | ## Introduction 6 | This is simple class for SELECT, INSERT, UPDATE, DELETE query for MySQL 7 | 8 | ## Installation 9 | `composer require hadi/database` 10 | 11 | if you don't want composer then simple grab class file from src/Database.php and use it! 12 | 13 | ## Usage 14 | 15 | ### Connection 16 | ```php 17 | $config = [ 18 | 'host' => 'localhost', 19 | 'name' => 'temp', 20 | 'username' => 'root', 21 | 'password' => '', 22 | ]; 23 | 24 | $db = new \Hadi\Database(); 25 | $db->connect($config); 26 | ``` 27 | 28 | ### Disconnect 29 | ```php 30 | $db->disconnect(); 31 | ``` 32 | 33 | ### Select Query 34 | 35 | #### Method #1 36 | ```php 37 | $db->query('SELECT * FROM users')->get(); 38 | ``` 39 | 40 | ```php 41 | $db->query('SELECT * FROM users')->first(); 42 | ``` 43 | 44 | #### Method #2 45 | 46 | ```php 47 | $db->table('users')->select([ 48 | 'field' => ['name', 'username'], 49 | ])->first(); 50 | ``` 51 | 52 | ```php 53 | $db->table('users')->select([ 54 | 'field' => ['name', 'username'], 55 | 'condition' => 'WHERE id > 0', 56 | 'limit' => '0, 10', 57 | 'orderby' => 'name', 58 | 'groupby' => 'name', 59 | ])->first(); 60 | ``` 61 | 62 | ### Insert 63 | 64 | Insert data: 65 | ```php 66 | $db->table('users')->insert(['name' => 'John doe', 'email' => 'john@email.com']); 67 | ``` 68 | 69 | Insert data when supplied email `john@email.com` not exists in table `users`: 70 | 71 | ```php 72 | $db->table('users')->insert( 73 | ['name' => 'John doe', 'email' => 'john@email.com'], 74 | ['email'] 75 | ); 76 | ``` 77 | 78 | ##### result 79 | 80 | ``` 81 | affected_row 82 | inserted_id 83 | is_duplicate 84 | ``` 85 | 86 | ### Update 87 | 88 | Update data where `id = 1` 89 | ```php 90 | $db->table('users')->update( 91 | ['name' => 'John doe', 'email' => 'john@email.com'], 92 | ['id' => 1] 93 | ); 94 | ``` 95 | 96 | or 97 | ```php 98 | $db->table('users')->update( 99 | ['username' => 'johndoe'], 100 | 'id = 1' 101 | ); 102 | ``` 103 | 104 | update `username` if nobody else using same username 105 | 106 | ```php 107 | $db->table('users')->update( 108 | ['username' => 'johndoe'], 109 | ['id' => 4], 110 | ['username'] 111 | ); 112 | ``` 113 | 114 | ##### result 115 | ``` 116 | affected_row 117 | is_duplicate 118 | ``` 119 | 120 | ### Delete 121 | ```php 122 | $db->table('users')->delete(['id' => 4]); 123 | ``` 124 | 125 | ##### result 126 | ``` 127 | affected_row 128 | ``` 129 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hadi/database", 3 | "description": "Simple database driver for mysql (PDO)", 4 | "type": "package", 5 | "license": "MIT", 6 | "authors": [ 7 | { 8 | "name": "Habib Hadi", 9 | "email": "me@habibhadi.com" 10 | } 11 | ], 12 | "require": { 13 | "php": ">=5.3.0" 14 | }, 15 | "autoload": { 16 | "psr-4": {"Hadi\\": "src/"} 17 | }, 18 | "minimum-stability": "stable", 19 | "version": "1.0.1" 20 | } 21 | -------------------------------------------------------------------------------- /src/Database.php: -------------------------------------------------------------------------------- 1 | \PDO::ERRMODE_EXCEPTION, 38 | \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'" 39 | ); 40 | 41 | $this->pdo = new \PDO($dsn, $config['username'], $config['password'], $opt); 42 | 43 | return $this->pdo; 44 | } catch (PDOException $ex) { 45 | echo $this->dbErrorMsg . $ex->getMessage(); 46 | exit(); 47 | } 48 | } 49 | 50 | 51 | /** 52 | * Disconnect from database 53 | * 54 | * @return bool 55 | */ 56 | public function disconnect() 57 | { 58 | $this->pdo = NULL; 59 | 60 | return true; 61 | } 62 | 63 | 64 | /** 65 | * Get all result 66 | * 67 | * @return mixed 68 | */ 69 | public function get() 70 | { 71 | return $this->result; 72 | } 73 | 74 | 75 | /** 76 | * Get first data 77 | * 78 | * @return null 79 | */ 80 | public function first() 81 | { 82 | if ($this->result) { 83 | return count($this->result) > 0 ? $this->result[0] : NULL; 84 | } 85 | 86 | return NULL; 87 | } 88 | 89 | 90 | public function debug() 91 | { 92 | return $this->queryDebug; 93 | } 94 | 95 | public function total() 96 | { 97 | return $this->total; 98 | } 99 | 100 | 101 | /** 102 | * If string starts with 103 | * 104 | * @param $haystack 105 | * @param $needle 106 | * @return bool 107 | */ 108 | protected function startsWith($haystack, $needle) 109 | { 110 | return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE; 111 | } 112 | 113 | 114 | /** 115 | * General query 116 | * 117 | * @param $queryString 118 | * @param int $method 119 | * @return $this 120 | */ 121 | public function query($queryString, $method = NULL) 122 | { 123 | if (!$method) { 124 | $method = $this->fetchMethod; 125 | } 126 | 127 | try { 128 | // query 129 | $qry = $this->pdo->prepare($queryString); 130 | $qry->execute(); 131 | $qry->setFetchMode($method); 132 | 133 | // stroring data arrary into $result 134 | if ($this->startsWith($queryString, "SELECT")) { 135 | $this->result = $qry->fetchAll(); 136 | } 137 | 138 | // total row count 139 | $this->total = $qry->rowCount(); 140 | 141 | $this->queryDebug = ['string' => $queryString, 'value' => NULL, 'method' => $method]; 142 | 143 | } catch (PDOException $ex) { 144 | echo $this->dbErrorMsg . $ex->getMessage(); 145 | exit(); 146 | } 147 | 148 | return $this; 149 | } 150 | 151 | 152 | /** 153 | * Select table 154 | * 155 | * @param $tableName 156 | * @return $this 157 | */ 158 | public function table($tableName) 159 | { 160 | $this->tableName = $tableName; 161 | 162 | return $this; 163 | } 164 | 165 | 166 | /** 167 | * Select query 168 | * 169 | * @param array $qryArray 170 | * @return $this 171 | */ 172 | public function select($qryArray = []) 173 | { 174 | $fetchFields = (isset($qryArray['field']) && count($qryArray['field'])>0) ? implode(', ',$qryArray['field']): '*'; 175 | 176 | $qryStr = 'SELECT '.$fetchFields.' FROM `'.$this->tableName.'` '.((isset($qryArray['condition']) && $qryArray['condition']!=NULL)?$qryArray['condition']:''); 177 | 178 | if(isset($qryArray['groupby']) && $qryArray['groupby'] != NULL) { 179 | $qryStr .= ' GROUP BY '.$qryArray['groupby']; 180 | } 181 | 182 | if(isset($qryArray['orderby']) && $qryArray['orderby'] != NULL) { 183 | $qryStr .= ' ORDER BY '.$qryArray['orderby']; 184 | } 185 | 186 | if(isset($qryArray['limit']) && $qryArray['limit'] != NULL) { 187 | $qryStr .= ' LIMIT '.$qryArray['limit']; 188 | } 189 | 190 | try { 191 | $qry = $this->pdo->prepare($qryStr); 192 | $qry->execute(); 193 | 194 | if(isset($qryArray['method']) && $qryArray['method']!=NULL) { 195 | $qry->setFetchMode($qryArray['method']); 196 | } 197 | else { 198 | $qry->setFetchMode($this->fetchMethod); 199 | } 200 | 201 | $this->result = $qry->fetchAll(); 202 | 203 | $this->total = $qry->rowCount(); 204 | 205 | $this->queryDebug = ['string' => $qryStr, 'value' => NULL, 'method' => (isset($qryArray['method']) ? $qryArray['method'] : $this->fetchMethod)]; 206 | } 207 | catch (PDOException $ex){ 208 | echo $this->dbErrorMsg . $ex->getMessage(). ' query: '.$qryStr; 209 | exit(); 210 | } 211 | 212 | return $this; 213 | } 214 | 215 | 216 | /** 217 | * Insert operation 218 | * 219 | * @param array $dataArray 220 | * @param array $unique 221 | * @return array 222 | */ 223 | public function insert($dataArray = [], $unique = []) 224 | { 225 | $fields = []; 226 | $executeArray = []; 227 | $duplicate = false; 228 | 229 | // populating field array 230 | foreach($dataArray as $key=>$val){ 231 | $fields[] = ':'.$key; 232 | $executeArray[':'.$key] = $val; 233 | 234 | } 235 | 236 | // generating field string 237 | $fields_str = implode(',',$fields); 238 | $rawFieldsStr = implode(',', str_replace(':','',$fields)); 239 | 240 | // checking wheather same value exists or not 241 | if( count($unique) > 0 ){ 242 | $condition = array(); 243 | foreach($unique as $fieldName){ 244 | $condition[] = $fieldName." = '".$dataArray[$fieldName]."' "; 245 | } 246 | 247 | $cQryStr = "SELECT ".$unique[0]." FROM ".$this->tableName." WHERE ".implode('AND ',$condition); 248 | $cQry = $this->pdo->query($cQryStr); 249 | 250 | // checking duplicate 251 | if( $cQry->rowCount() > 0 ) $duplicate = true; 252 | else $duplicate = false; 253 | } 254 | 255 | $affectedRow = 0; 256 | $lastInsertedId = 0; 257 | 258 | // processing insertsion while there is no duplicated value 259 | if(!$duplicate) { 260 | $qryStr = 'INSERT INTO '.$this->tableName.' ('.$rawFieldsStr.') VALUES('.$fields_str.')'; 261 | 262 | try { 263 | // query 264 | $qry = $this->pdo->prepare($qryStr); 265 | $qry->execute($executeArray); 266 | 267 | // affected row 268 | $affectedRow = $qry->rowCount(); 269 | 270 | // last inseretd id 271 | $lastInsertedId = $this->pdo->lastInsertId(); 272 | 273 | $this->queryDebug = ['string' => $qryStr, 'value' => $executeArray, 'method' => false]; 274 | } 275 | catch (PDOException $ex){ 276 | echo $this->dbErrorMsg . $ex->getMessage(); 277 | exit(); 278 | } 279 | } 280 | 281 | // returning insert log 282 | return [ 283 | 'affected_row' => $affectedRow, 284 | 'inserted_id' => $lastInsertedId, 285 | 'is_duplicate' => (bool) $duplicate 286 | ]; 287 | } 288 | 289 | public function update($dataArray = [], $where, $unique = []) 290 | { 291 | $tableName = $this->tableName; 292 | 293 | $fields = []; 294 | $executeArray = []; 295 | 296 | // populating field array 297 | foreach($dataArray as $key=>$val){ 298 | $fields[] = $key.' = :'.$key; 299 | $executeArray[':'.$key] = $val; 300 | 301 | } 302 | 303 | // generating field string 304 | $fields_str = implode(', ',$fields); 305 | 306 | // checking wheather same value exists or not 307 | if( count($unique) > 0 ){ 308 | $condition = []; 309 | 310 | foreach($unique as $fieldName){ 311 | $condition[] = $fieldName." = '".$dataArray[$fieldName]."' "; 312 | } 313 | 314 | $extendedCondition = []; 315 | 316 | if( is_array($where) && count($where) > 0 ){ 317 | foreach($where as $whereKey=>$whereVal){ 318 | $extendedCondition[] = $whereKey." != '".$whereVal."' "; 319 | } 320 | } 321 | 322 | $cQryStr = "SELECT ".$unique[0]." FROM ".$tableName." WHERE ".implode('AND ',$condition); 323 | if( count($extendedCondition) > 0 ) $cQryStr .= "AND ".implode('AND ', $extendedCondition); 324 | 325 | $cQry = $this->pdo->query($cQryStr); 326 | 327 | // checking duplicate 328 | if( $cQry->rowCount() > 0 ) $duplicate = true; 329 | else $duplicate = false; 330 | } 331 | else { 332 | $duplicate = false; 333 | } 334 | 335 | $affectedRow = 0; 336 | 337 | // processing query while there is no duplicated value 338 | if(!$duplicate && ($where!=NULL || (is_array($where) && count($where)>0)) ) { 339 | 340 | if(is_array($where)) { 341 | $affectedTo = []; 342 | 343 | foreach($where as $key=>$val){ 344 | $affectedTo[] = $key." = '".$val."'"; 345 | } 346 | 347 | $whereCond = ' WHERE '.implode(" AND ", $affectedTo); 348 | } 349 | else { 350 | $whereCond = ' WHERE '.$where; 351 | } 352 | 353 | $qryStr = 'UPDATE '.$tableName.' SET '.$fields_str.$whereCond; 354 | 355 | try { 356 | // query 357 | $qry = $this->pdo->prepare($qryStr); 358 | $qry->execute($executeArray); 359 | 360 | // affected row 361 | $affectedRow = $qry->rowCount(); 362 | 363 | $this->queryDebug = ['string' => $qryStr, 'value' => $executeArray, 'method' => false]; 364 | 365 | } 366 | catch (PDOException $ex){ 367 | echo $this->dbErrorMsg . $ex->getMessage(); 368 | exit(); 369 | } 370 | } 371 | else { 372 | $this->queryDebug = ['string' => $cQryStr, 'value' => NULL, 'method' => $this->fetchMethod]; 373 | } 374 | 375 | // returning insert log 376 | return [ 377 | 'affected_row' => $affectedRow, 378 | 'is_duplicate' => (bool) $duplicate 379 | ]; 380 | } 381 | 382 | 383 | /** 384 | * Delete operation 385 | * 386 | * @param $where 387 | * @return array 388 | */ 389 | public function delete($where) 390 | { 391 | $tableName = $this->tableName; 392 | 393 | $affectedRow = 0; 394 | if($where!=NULL || (is_array($where) && count($where)) > 0 ){ 395 | if(is_array($where)) { 396 | $affectedTo = array(); 397 | foreach($where as $key=>$val){ 398 | $affectedTo[] = $key." = '".$val."'"; 399 | } 400 | $whereCond = 'WHERE '.implode(" AND ", $affectedTo); 401 | } 402 | else { 403 | $whereCond = 'WHERE '.$where; 404 | } 405 | 406 | $qryStr = 'DELETE FROM '.$tableName.' '.$whereCond; 407 | 408 | try { 409 | // query 410 | $qry = $this->pdo->prepare($qryStr); 411 | $qry->execute(); 412 | 413 | // affected row 414 | $affectedRow = $qry->rowCount(); 415 | 416 | $this->queryDebug = ['string' => $qryStr, 'value' => NULL, 'method' => false]; 417 | 418 | } 419 | catch (PDOException $ex){ 420 | echo $this->dbErrorMsg . $ex->getMessage(); 421 | exit(); 422 | } 423 | } 424 | 425 | return [ 426 | 'affected_row' => $affectedRow 427 | ]; 428 | } 429 | 430 | } 431 | -------------------------------------------------------------------------------- /tests/test.php: -------------------------------------------------------------------------------- 1 | dbErrorMsg = 'sssss'; 6 | var_dump($database); --------------------------------------------------------------------------------