Repository: indieteq/indieteq-php-my-sql-pdo-database-class Branch: master Commit: 72eb816e4cff Files: 11 Total size: 28.1 KB Directory structure: gitextract_d3ec_8g3/ ├── Db.class.php ├── LICENSE ├── Log.class.php ├── README.md ├── SQL dump/ │ └── testdb.sql ├── composer.json ├── easyCRUD/ │ ├── Person.class.php │ ├── easyCRUD.class.php │ └── index.php ├── index.php └── settings.ini.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: Db.class.php ================================================ log = new Log(); $this->Connect(); $this->parameters = array(); } /** * This method makes connection to the database. * * 1. Reads the database settings from a ini file. * 2. Puts the ini content into the settings array. * 3. Tries to connect to the database. * 4. If connection failed, exception is displayed and a log file gets created. */ private function Connect() { $this->settings = parse_ini_file("settings.ini.php"); $dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' . $this->settings["host"] . ''; try { # Read settings from INI file, set UTF8 $this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"], array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" )); # We can now log any exceptions on Fatal error. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # Disable emulation of prepared statements, use REAL prepared statements instead. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); # Connection succeeded, set the boolean to true. $this->bConnected = true; } catch (PDOException $e) { # Write into log echo $this->ExceptionLog($e->getMessage()); die(); } } /* * You can use this little method if you want to close the PDO connection * */ public function CloseConnection() { # Set the PDO object to null to close the connection # http://www.php.net/manual/en/pdo.connections.php $this->pdo = null; } /** * Every method which needs to execute a SQL query uses this method. * * 1. If not connected, connect to the database. * 2. Prepare Query. * 3. Parameterize Query. * 4. Execute Query. * 5. On exception : Write Exception into the log + SQL query. * 6. Reset the Parameters. */ private function Init($query, $parameters = "") { # Connect to database if (!$this->bConnected) { $this->Connect(); } try { # Prepare query $this->sQuery = $this->pdo->prepare($query); # Add parameters to the parameter array $this->bindMore($parameters); # Bind parameters if (!empty($this->parameters)) { foreach ($this->parameters as $param => $value) { if(is_int($value[1])) { $type = PDO::PARAM_INT; } else if(is_bool($value[1])) { $type = PDO::PARAM_BOOL; } else if(is_null($value[1])) { $type = PDO::PARAM_NULL; } else { $type = PDO::PARAM_STR; } // Add type when binding the values to the column $this->sQuery->bindValue($value[0], $value[1], $type); } } # Execute SQL $this->sQuery->execute(); } catch (PDOException $e) { # Write into log and display Exception echo $this->ExceptionLog($e->getMessage(), $query); die(); } # Reset the parameters $this->parameters = array(); } /** * @void * * Add the parameter to the parameter array * @param string $para * @param string $value */ public function bind($para, $value) { $this->parameters[sizeof($this->parameters)] = [":" . $para , $value]; } /** * @void * * Add more parameters to the parameter array * @param array $parray */ public function bindMore($parray) { if (empty($this->parameters) && is_array($parray)) { $columns = array_keys($parray); foreach ($columns as $i => &$column) { $this->bind($column, $parray[$column]); } } } /** * If the SQL query contains a SELECT or SHOW statement it returns an array containing all of the result set row * If the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows * * @param string $query * @param array $params * @param int $fetchmode * @return mixed */ public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC) { $query = trim(str_replace("\r", " ", $query)); $this->Init($query, $params); $rawStatement = explode(" ", preg_replace("/\s+|\t+|\n+/", " ", $query)); # Which SQL statement is used $statement = strtolower($rawStatement[0]); if ($statement === 'select' || $statement === 'show') { return $this->sQuery->fetchAll($fetchmode); } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') { return $this->sQuery->rowCount(); } else { return NULL; } } /** * Returns the last inserted id. * @return string */ public function lastInsertId() { return $this->pdo->lastInsertId(); } /** * Starts the transaction * @return boolean, true on success or false on failure */ public function beginTransaction() { return $this->pdo->beginTransaction(); } /** * Execute Transaction * @return boolean, true on success or false on failure */ public function executeTransaction() { return $this->pdo->commit(); } /** * Rollback of Transaction * @return boolean, true on success or false on failure */ public function rollBack() { return $this->pdo->rollBack(); } /** * Returns an array which represents a column from the result set * * @param string $query * @param array $params * @return array */ public function column($query, $params = null) { $this->Init($query, $params); $Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM); $column = null; foreach ($Columns as $cells) { $column[] = $cells[0]; } return $column; } /** * Returns an array which represents a row from the result set * * @param string $query * @param array $params * @param int $fetchmode * @return array */ public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC) { $this->Init($query, $params); $result = $this->sQuery->fetch($fetchmode); $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued, return $result; } /** * Returns the value of one single field/column * * @param string $query * @param array $params * @return string */ public function single($query, $params = null) { $this->Init($query, $params); $result = $this->sQuery->fetchColumn(); $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued return $result; } /** * Writes the log and returns the exception * * @param string $message * @param string $sql * @return string */ private function ExceptionLog($message, $sql = "") { $exception = 'Unhandled Exception.
'; $exception .= $message; $exception .= "
You can find the error back in the log."; if (!empty($sql)) { # Add the Raw SQL to the Log $message .= "\r\nRaw SQL : " . $sql; } # Write into log $this->log->write($message); return $exception; } } ?> ================================================ FILE: LICENSE ================================================ /* * ---------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" * If we meet some day, and you think * this stuff is worth it, you can buy me a beer in return. * ---------------------------------------------------------------------------- */ ================================================ FILE: Log.class.php ================================================ path = dirname(__FILE__) . $this->path; } /** * @void * Creates the log * * @param string $message the message which is written into the log. * @description: * 1. Checks if directory exists, if not, create one and call this method again. * 2. Checks if log already exists. * 3. If not, new log gets created. Log is written into the logs folder. * 4. Logname is current date(Year - Month - Day). * 5. If log exists, edit method called. * 6. Edit method modifies the current log. */ public function write($message) { $date = new DateTime(); $log = $this->path . $date->format('Y-m-d').".txt"; if(is_dir($this->path)) { if(!file_exists($log)) { $fh = fopen($log, 'a+') or die("Fatal Error !"); $logcontent = "Time : " . $date->format('H:i:s')."\r\n" . $message ."\r\n"; fwrite($fh, $logcontent); fclose($fh); } else { $this->edit($log,$date, $message); } } else { if(mkdir($this->path,0777) === true) { $this->write($message); } } } /** * @void * Gets called if log exists. * Modifies current log and adds the message to the log. * * @param string $log * @param DateTimeObject $date * @param string $message */ private function edit($log,$date,$message) { $logcontent = "Time : " . $date->format('H:i:s')."\r\n" . $message ."\r\n\r\n"; $logcontent = $logcontent . file_get_contents($log); file_put_contents($log, $logcontent); } } ?> ================================================ FILE: README.md ================================================ I am not maintaining this repository anymore and I would like to request you to find a better repo or make a fork of this repository! ============================ PDO Database Class ============================ A database class for PHP-MySQL which uses the PDO extension. ## To use the class #### 1. Edit the database settings in the settings.ini.php ### Note if PDO is loading slow change localhost to -> 127.0.0.1 ! ``` [SQL] host = 127.0.0.1 user = root password = dbname = yourdatabase ``` #### 2. Require the class in your project ```php query("SELECT * FROM persons"); ``` #### Fetching with Bindings (ANTI-SQL-INJECTION): Binding parameters is the best way to prevent SQL injection. The class prepares your SQL query and binds the parameters afterwards. There are three different ways to bind parameters. ```php bind("id","1"); $db->bind("firstname","John"); $person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id"); // 2. Bind more parameters $db->bindMore(array("firstname"=>"John","id"=>"1")); $person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id")); // 3. Or just give the parameters to the method $person = $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND id = :id",array("firstname"=>"John","id"=>"1")); ``` More about SQL injection prevention : http://indieteq.com/index/readmore/how-to-prevent-sql-injection-in-php #### Fetching Row: This method always returns only 1 row. ```php row("SELECT * FROM Persons WHERE id = :id", array("id"=>"1")); ``` ##### Result | id | firstname | lastname | sex | age |:-----------:|:------------:|:------------:|:------------:|:------------:| | 1 | John | Doe | M | 19 #### Fetching Single Value: This method returns only one single value of a record. ```php bind("id","3"); $firstname = $db->single("SELECT firstname FROM Persons WHERE id = :id"); ``` ##### Result |firstname |:------------: | Zoe #### Using the like keyword ```php query("SELECT * FROM Persons WHERE Firstname LIKE :firstname ", array("firstname"=>"sekit%")); ``` ##### Result | id | firstname | lastname | sex | age |:-----------:|:------------:|:------------:|:------------:|:------------:| | 4 | Sekito | Khan | M | 19 #### Fetching Column: ```php column("SELECT Firstname FROM Persons"); ``` ##### Result |firstname | |:-----------: | John | Bob | Zoe | Kona | Kader ### Delete / Update / Insert When executing the delete, update, or insert statement by using the query method the affected rows will be returned. ```php query("DELETE FROM Persons WHERE Id = :id", array("id"=>"1")); // Update $update = $db->query("UPDATE Persons SET firstname = :f WHERE Id = :id", array("f"=>"Jan","id"=>"32")); // Insert $insert = $db->query("INSERT INTO Persons(Firstname,Age) VALUES(:f,:age)", array("f"=>"Vivek","age"=>"20")); // Do something with the data if($insert > 0 ) { return 'Succesfully created a new person !'; } ``` ## Method parameters Every method which executes a query has the optional parameter called bindings. The row and the query method have a third optional parameter which is the fetch style. The default fetch style is PDO::FETCH_ASSOC which returns an associative array. Here an example : ```php row("SELECT * FROM Persons WHERE id = :id", array("id"=>"1"), PDO::FETCH_NUM); print_r($person_num); // Array ( [0] => 1 [1] => Johny [2] => Doe [3] => M [4] => 19 ) ``` More info about the PDO fetchstyle : http://php.net/manual/en/pdostatement.fetch.php EasyCRUD ============================ The easyCRUD is a class which you can use to easily execute basic SQL operations like(insert, update, select, delete) on your database. It uses the database class I've created to execute the SQL queries. Actually it's just a little ORM class. ## How to use easyCRUD #### 1. First, create a new class. Then require the easyCRUD class. #### 2. Extend your class to the base class Crud and add the following fields to the class. #### Example class : ```php Firstname = "Kona"; $person->Age = "20"; $person->Sex = "F"; $created = $person->Create(); // Or give the bindings to the constructor $person = new person(array("Firstname"=>"Kona","age"=>"20","sex"=>"F")); $created = $person->Create(); // SQL Equivalent "INSERT INTO persons (Firstname,Age,Sex) VALUES ('Kona','20','F')" ``` #### Deleting a person ```php Id = "17"; $deleted = $person->Delete(); // Shorthand method, give id as parameter $deleted = $person->Delete(17); // SQL Equivalent "DELETE FROM persons WHERE Id = 17 LIMIT 1" ``` #### Saving person's data ```php Firstname = "John"; $person->Age = "20"; $person->Sex = "F"; $person->Id = "4"; // Returns affected rows $saved = $person->Save(); // Or give the bindings to the constructor $person = new person(array("Firstname"=>"John","age"=>"20","sex"=>"F","Id"=>"4")); $saved = $person->Save(); // SQL Equivalent "UPDATE persons SET Firstname = 'John',Age = 20, Sex = 'F' WHERE Id= 4" ``` #### Finding a person ```php Id = "1"; $person->find(); echo $person->Firstname; // Johny // Shorthand method, give id as parameter $person->find(1); // SQL Equivalent "SELECT * FROM persons WHERE Id = 1" ``` #### Getting all the persons ```php all(); // SQL Equivalent "SELECT * FROM persons ``` ## Copyright and license #### Code released under Beerware ================================================ FILE: SQL dump/testdb.sql ================================================ /* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50527 Source Host : localhost:3306 Source Database : testdb Target Server Type : MYSQL Target Server Version : 50527 File Encoding : 65001 Date: 2012-11-12 14:07:39 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `persons` -- ---------------------------- DROP TABLE IF EXISTS `persons`; CREATE TABLE `persons` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Firstname` varchar(32) DEFAULT NULL, `Lastname` varchar(32) DEFAULT NULL, `Sex` char(1) DEFAULT NULL, `Age` tinyint(3) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; -- ---------------------------- -- Records of persons -- ---------------------------- INSERT INTO `persons` VALUES ('1', 'John', 'Doe', 'M', '19'); INSERT INTO `persons` VALUES ('2', 'Bob', 'Black', 'M', '40'); INSERT INTO `persons` VALUES ('3', 'Zoe', 'Chan', 'F', '21'); INSERT INTO `persons` VALUES ('4', 'Sekito', 'Khan', 'M', '19'); INSERT INTO `persons` VALUES ('5', 'Kader', 'Khan', 'M', '56'); ================================================ FILE: composer.json ================================================ { "name": "indieteq/indieteq-php-my-sql-pdo-database-class", "description": "A database class for MySQL with PDO", "type": "library", "keywords": [ "mysql", "pdo", "php", "beer", "free" ], "homepage": "https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class", "license": "Beerware", "authors": [ { "name": "wicky", "email": "info@wickyaswal.com" } ], "require": { "php": ">=5.3.0" } } ================================================ FILE: easyCRUD/Person.class.php ================================================ ================================================ FILE: easyCRUD/easyCRUD.class.php ================================================ db = new DB(); $this->variables = $data; } public function __set($name,$value){ if(strtolower($name) === $this->pk) { $this->variables[$this->pk] = $value; } else { $this->variables[$name] = $value; } } public function __get($name) { if(is_array($this->variables)) { if(array_key_exists($name,$this->variables)) { return $this->variables[$name]; } } return null; } public function save($id = "0") { $this->variables[$this->pk] = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; $fieldsvals = ''; $columns = array_keys($this->variables); foreach($columns as $column) { if($column !== $this->pk) $fieldsvals .= $column . " = :". $column . ","; } $fieldsvals = substr_replace($fieldsvals , '', -1); if(count($columns) > 1 ) { $sql = "UPDATE " . $this->table . " SET " . $fieldsvals . " WHERE " . $this->pk . "= :" . $this->pk; if($id === "0" && $this->variables[$this->pk] === "0") { unset($this->variables[$this->pk]); $sql = "UPDATE " . $this->table . " SET " . $fieldsvals; } return $this->exec($sql); } return null; } public function create() { $bindings = $this->variables; if(!empty($bindings)) { $fields = array_keys($bindings); $fieldsvals = array(implode(",",$fields),":" . implode(",:",$fields)); $sql = "INSERT INTO ".$this->table." (".$fieldsvals[0].") VALUES (".$fieldsvals[1].")"; } else { $sql = "INSERT INTO ".$this->table." () VALUES ()"; } return $this->exec($sql); } public function delete($id = "") { $id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; if(!empty($id)) { $sql = "DELETE FROM " . $this->table . " WHERE " . $this->pk . "= :" . $this->pk. " LIMIT 1" ; } return $this->exec($sql, array($this->pk=>$id)); } public function find($id = "") { $id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; if(!empty($id)) { $sql = "SELECT * FROM " . $this->table ." WHERE " . $this->pk . "= :" . $this->pk . " LIMIT 1"; $result = $this->db->row($sql, array($this->pk=>$id)); $this->variables = ($result != false) ? $result : null; } } /** * @param array $fields. * @param array $sort. * @return array of Collection. * Example: $user = new User; * $found_user_array = $user->search(array('sex' => 'Male', 'age' => '18'), array('dob' => 'DESC')); * // Will produce: SELECT * FROM {$this->table_name} WHERE sex = :sex AND age = :age ORDER BY dob DESC; * // And rest is binding those params with the Query. Which will return an array. * // Now we can use for each on $found_user_array. * Other functionalities ex: Support for LIKE, >, <, >=, <= ... Are not yet supported. */ public function search($fields = array(), $sort = array()) { $bindings = empty($fields) ? $this->variables : $fields; $sql = "SELECT * FROM " . $this->table; if (!empty($bindings)) { $fieldsvals = array(); $columns = array_keys($bindings); foreach($columns as $column) { $fieldsvals [] = $column . " = :". $column; } $sql .= " WHERE " . implode(" AND ", $fieldsvals); } if (!empty($sort)) { $sortvals = array(); foreach ($sort as $key => $value) { $sortvals[] = $key . " " . $value; } $sql .= " ORDER BY " . implode(", ", $sortvals); } return $this->exec($sql); } public function all(){ return $this->db->query("SELECT * FROM " . $this->table); } public function min($field) { if($field) return $this->db->single("SELECT min(" . $field . ")" . " FROM " . $this->table); } public function max($field) { if($field) return $this->db->single("SELECT max(" . $field . ")" . " FROM " . $this->table); } public function avg($field) { if($field) return $this->db->single("SELECT avg(" . $field . ")" . " FROM " . $this->table); } public function sum($field) { if($field) return $this->db->single("SELECT sum(" . $field . ")" . " FROM " . $this->table); } public function count($field) { if($field) return $this->db->single("SELECT count(" . $field . ")" . " FROM " . $this->table); } private function exec($sql, $array = null) { if($array !== null) { // Get result with the DB object $result = $this->db->query($sql, $array); } else { // Get result with the DB object $result = $this->db->query($sql, $this->variables); } // Empty bindings $this->variables = array(); return $result; } } ?> ================================================ FILE: easyCRUD/index.php ================================================ Firstname = "Kona"; $person->Age = "20"; $person->Sex = "F"; $creation = $person->Create(); // Update Person Info $person->id = "4"; $person->Age = "32"; $saved = $person->Save(); // Find person $person->id = "4"; $person->Find(); d($person->Firstname, "Person->Firstname"); d($person->Age, "Person->Age"); // Delete person $person->id = "17"; $delete = $person->Delete(); // Get all persons $persons = $person->all(); // Aggregates methods d($person->max('age'), "Max person age"); d($person->min('age'), "Min person age"); d($person->sum('age'), "Sum persons age"); d($person->avg('age'), "Average persons age"); d($person->count('id'), "Count persons"); function d($v, $t = "") { echo '
';
      echo '

' . $t. '

'; var_dump($v); echo '
'; } ?> ================================================ FILE: index.php ================================================ bind("firstname","John"); $db->bind("age","19"); // 2. Bind more parameters $db->bindMore(array("firstname"=>"John","age"=>"19")); // 3. Or just give the parameters to the method $db->query("SELECT * FROM Persons WHERE firstname = :firstname AND age = :age", array("firstname"=>"John","age"=>"19")); // Fetching data $person = $db->query("SELECT * FROM Persons"); // If you want another fetchmode just give it as parameter $persons_num = $db->query("SELECT * FROM Persons", null, PDO::FETCH_NUM); // Fetching single value $firstname = $db->single("SELECT firstname FROM Persons WHERE Id = :id ", array('id' => '3' ) ); // Single Row $id_age = $db->row("SELECT Id, Age FROM Persons WHERE firstname = :f", array("f"=>"Zoe")); // Single Row with numeric index $id_age_num = $db->row("SELECT Id, Age FROM Persons WHERE firstname = :f", array("f"=>"Zoe"),PDO::FETCH_NUM); // Column, numeric index $ages = $db->column("SELECT age FROM Persons"); // The following statements will return the affected rows // Update statement $update = $db->query("UPDATE Persons SET firstname = :f WHERE Id = :id",array("f"=>"Johny","id"=>"1")); // Insert statement // $insert = $db->query("INSERT INTO Persons(Firstname,Age) VALUES(:f,:age)",array("f"=>"Vivek","age"=>"20")); // Delete statement // $delete = $db->query("DELETE FROM Persons WHERE Id = :id",array("id"=>"6")); function d($v, $t = "") { echo '
';
		echo '

' . $t. '

'; var_dump($v); echo '
'; } //d($person, "All persons"); d($id_age, "Single Row, Id and Age"); d($firstname, "Fetch Single value, The firstname"); d($ages, "Fetch Column, Numeric Index"); ?> ================================================ FILE: settings.ini.php ================================================ ; [SQL] host = localhost user = root password = dbname = testdb