[
  {
    "path": "Db.class.php",
    "content": "<?php\n/**\n *  DB - A simple database class \n *\n * @author\t\tAuthor: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)\n * @git \t\thttps://github.com/wickyaswal/PHP-MySQL-PDO-Database-Class\n * @version      0.2ab\n *\n */\nrequire(\"Log.class.php\");\nclass DB\n{\n    # @object, The PDO object\n    private $pdo;\n    \n    # @object, PDO statement object\n    private $sQuery;\n    \n    # @array,  The database settings\n    private $settings;\n    \n    # @bool ,  Connected to the database\n    private $bConnected = false;\n    \n    # @object, Object for logging exceptions\t\n    private $log;\n    \n    # @array, The parameters of the SQL query\n    private $parameters;\n    \n    /**\n     *   Default Constructor \n     *\n     *\t1. Instantiate Log class.\n     *\t2. Connect to database.\n     *\t3. Creates the parameter array.\n     */\n    public function __construct()\n    {\n        $this->log = new Log();\n        $this->Connect();\n        $this->parameters = array();\n    }\n    \n    /**\n     *\tThis method makes connection to the database.\n     *\t\n     *\t1. Reads the database settings from a ini file. \n     *\t2. Puts  the ini content into the settings array.\n     *\t3. Tries to connect to the database.\n     *\t4. If connection failed, exception is displayed and a log file gets created.\n     */\n    private function Connect()\n    {\n        $this->settings = parse_ini_file(\"settings.ini.php\");\n        $dsn            = 'mysql:dbname=' . $this->settings[\"dbname\"] . ';host=' . $this->settings[\"host\"] . '';\n        try {\n            # Read settings from INI file, set UTF8\n            $this->pdo = new PDO($dsn, $this->settings[\"user\"], $this->settings[\"password\"], array(\n                PDO::MYSQL_ATTR_INIT_COMMAND => \"SET NAMES utf8\"\n            ));\n            \n            # We can now log any exceptions on Fatal error. \n            $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n            \n            # Disable emulation of prepared statements, use REAL prepared statements instead.\n            $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);\n            \n            # Connection succeeded, set the boolean to true.\n            $this->bConnected = true;\n        }\n        catch (PDOException $e) {\n            # Write into log\n            echo $this->ExceptionLog($e->getMessage());\n            die();\n        }\n    }\n    /*\n     *   You can use this little method if you want to close the PDO connection\n     *\n     */\n    public function CloseConnection()\n    {\n        # Set the PDO object to null to close the connection\n        # http://www.php.net/manual/en/pdo.connections.php\n        $this->pdo = null;\n    }\n    \n    /**\n     *\tEvery method which needs to execute a SQL query uses this method.\n     *\t\n     *\t1. If not connected, connect to the database.\n     *\t2. Prepare Query.\n     *\t3. Parameterize Query.\n     *\t4. Execute Query.\t\n     *\t5. On exception : Write Exception into the log + SQL query.\n     *\t6. Reset the Parameters.\n     */\n    private function Init($query, $parameters = \"\")\n    {\n        # Connect to database\n        if (!$this->bConnected) {\n            $this->Connect();\n        }\n        try {\n            # Prepare query\n            $this->sQuery = $this->pdo->prepare($query);\n            \n            # Add parameters to the parameter array\t\n            $this->bindMore($parameters);\n            \n            # Bind parameters\n            if (!empty($this->parameters)) {\n                foreach ($this->parameters as $param => $value) {\n                    if(is_int($value[1])) {\n                        $type = PDO::PARAM_INT;\n                    } else if(is_bool($value[1])) {\n                        $type = PDO::PARAM_BOOL;\n                    } else if(is_null($value[1])) {\n                        $type = PDO::PARAM_NULL;\n                    } else {\n                        $type = PDO::PARAM_STR;\n                    }\n                    // Add type when binding the values to the column\n                    $this->sQuery->bindValue($value[0], $value[1], $type);\n                }\n            }\n            \n            # Execute SQL \n            $this->sQuery->execute();\n        }\n        catch (PDOException $e) {\n            # Write into log and display Exception\n            echo $this->ExceptionLog($e->getMessage(), $query);\n            die();\n        }\n        \n        # Reset the parameters\n        $this->parameters = array();\n    }\n    \n    /**\n     *\t@void \n     *\n     *\tAdd the parameter to the parameter array\n     *\t@param string $para  \n     *\t@param string $value \n     */\n    public function bind($para, $value)\n    {\n        $this->parameters[sizeof($this->parameters)] = [\":\" . $para , $value];\n    }\n    /**\n     *\t@void\n     *\t\n     *\tAdd more parameters to the parameter array\n     *\t@param array $parray\n     */\n    public function bindMore($parray)\n    {\n        if (empty($this->parameters) && is_array($parray)) {\n            $columns = array_keys($parray);\n            foreach ($columns as $i => &$column) {\n                $this->bind($column, $parray[$column]);\n            }\n        }\n    }\n    /**\n     *  If the SQL query  contains a SELECT or SHOW statement it returns an array containing all of the result set row\n     *\tIf the SQL statement is a DELETE, INSERT, or UPDATE statement it returns the number of affected rows\n     *\n     *   \t@param  string $query\n     *\t@param  array  $params\n     *\t@param  int    $fetchmode\n     *\t@return mixed\n     */\n    public function query($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)\n    {\n        $query = trim(str_replace(\"\\r\", \" \", $query));\n        \n        $this->Init($query, $params);\n        \n        $rawStatement = explode(\" \", preg_replace(\"/\\s+|\\t+|\\n+/\", \" \", $query));\n        \n        # Which SQL statement is used \n        $statement = strtolower($rawStatement[0]);\n        \n        if ($statement === 'select' || $statement === 'show') {\n            return $this->sQuery->fetchAll($fetchmode);\n        } elseif ($statement === 'insert' || $statement === 'update' || $statement === 'delete') {\n            return $this->sQuery->rowCount();\n        } else {\n            return NULL;\n        }\n    }\n    \n    /**\n     *  Returns the last inserted id.\n     *  @return string\n     */\n    public function lastInsertId()\n    {\n        return $this->pdo->lastInsertId();\n    }\n    \n    /**\n     * Starts the transaction\n     * @return boolean, true on success or false on failure\n     */\n    public function beginTransaction()\n    {\n        return $this->pdo->beginTransaction();\n    }\n    \n    /**\n     *  Execute Transaction\n     *  @return boolean, true on success or false on failure\n     */\n    public function executeTransaction()\n    {\n        return $this->pdo->commit();\n    }\n    \n    /**\n     *  Rollback of Transaction\n     *  @return boolean, true on success or false on failure\n     */\n    public function rollBack()\n    {\n        return $this->pdo->rollBack();\n    }\n    \n    /**\n     *\tReturns an array which represents a column from the result set \n     *\n     *\t@param  string $query\n     *\t@param  array  $params\n     *\t@return array\n     */\n    public function column($query, $params = null)\n    {\n        $this->Init($query, $params);\n        $Columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);\n        \n        $column = null;\n        \n        foreach ($Columns as $cells) {\n            $column[] = $cells[0];\n        }\n        \n        return $column;\n        \n    }\n    /**\n     *\tReturns an array which represents a row from the result set \n     *\n     *\t@param  string $query\n     *\t@param  array  $params\n     *   \t@param  int    $fetchmode\n     *\t@return array\n     */\n    public function row($query, $params = null, $fetchmode = PDO::FETCH_ASSOC)\n    {\n        $this->Init($query, $params);\n        $result = $this->sQuery->fetch($fetchmode);\n        $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued,\n        return $result;\n    }\n    /**\n     *\tReturns the value of one single field/column\n     *\n     *\t@param  string $query\n     *\t@param  array  $params\n     *\t@return string\n     */\n    public function single($query, $params = null)\n    {\n        $this->Init($query, $params);\n        $result = $this->sQuery->fetchColumn();\n        $this->sQuery->closeCursor(); // Frees up the connection to the server so that other SQL statements may be issued\n        return $result;\n    }\n    /**\t\n     * Writes the log and returns the exception\n     *\n     * @param  string $message\n     * @param  string $sql\n     * @return string\n     */\n    private function ExceptionLog($message, $sql = \"\")\n    {\n        $exception = 'Unhandled Exception. <br />';\n        $exception .= $message;\n        $exception .= \"<br /> You can find the error back in the log.\";\n        \n        if (!empty($sql)) {\n            # Add the Raw SQL to the Log\n            $message .= \"\\r\\nRaw SQL : \" . $sql;\n        }\n        # Write into log\n        $this->log->write($message);\n        \n        return $exception;\n    }\n}\n?>\n"
  },
  {
    "path": "LICENSE",
    "content": "/*\n * ----------------------------------------------------------------------------\n * \"THE BEER-WARE LICENSE\" \n * If we meet some day, and you think\n * this stuff is worth it, you can buy me a beer in return.\n * ----------------------------------------------------------------------------\n */"
  },
  {
    "path": "Log.class.php",
    "content": "<?php \n       /* *\n\t* Log \t\t\tA logger class which creates logs when an exception is thrown.\n\t* @author\t\tAuthor: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)\n\t* @git \t\t\thttps://github.com/wickyaswal/PHP-MySQL-PDO-Database-Class\n\t* @version      0.1a\n\t*/\n\tclass Log {\n\t\t\t\n\t\t    # @string, Log directory name\n\t\t    \tprivate $path = '/logs/';\n\t\t\t\n\t\t    # @void, Default Constructor, Sets the timezone and path of the log files.\n\t\t\tpublic function __construct() {\n\t\t\t\tdate_default_timezone_set('Europe/Amsterdam');\t\n\t\t\t\t$this->path  = dirname(__FILE__)  . $this->path;\t\n\t\t\t}\n\t\t\t\n\t\t   /**\n\t\t    *   @void \n\t\t    *\tCreates the log\n\t\t    *\n\t\t    *   @param string $message the message which is written into the log.\n\t\t    *\t@description:\n\t\t    *\t 1. Checks if directory exists, if not, create one and call this method again.\n\t            *\t 2. Checks if log already exists.\n\t\t    *\t 3. If not, new log gets created. Log is written into the logs folder.\n\t\t    *\t 4. Logname is current date(Year - Month - Day).\n\t\t    *\t 5. If log exists, edit method called.\n\t\t    *\t 6. Edit method modifies the current log.\n\t\t    */\t\n\t\t\tpublic function write($message) {\n\t\t\t\t$date = new DateTime();\n\t\t\t\t$log = $this->path . $date->format('Y-m-d').\".txt\";\n\n\t\t\t\tif(is_dir($this->path)) {\n\t\t\t\t\tif(!file_exists($log)) {\n\t\t\t\t\t\t$fh  = fopen($log, 'a+') or die(\"Fatal Error !\");\n\t\t\t\t\t\t$logcontent = \"Time : \" . $date->format('H:i:s').\"\\r\\n\" . $message .\"\\r\\n\";\n\t\t\t\t\t\tfwrite($fh, $logcontent);\n\t\t\t\t\t\tfclose($fh);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t$this->edit($log,$date, $message);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t  if(mkdir($this->path,0777) === true) \n\t\t\t\t\t  {\n \t\t\t\t\t\t $this->write($message);  \n\t\t\t\t\t  }\t\n\t\t\t\t}\n\t\t\t }\n\t\t\t\n\t\t\t/** \n\t\t\t *  @void\n\t\t\t *  Gets called if log exists. \n\t\t\t *  Modifies current log and adds the message to the log.\n\t\t\t *\n\t\t\t * @param string $log\n\t\t\t * @param DateTimeObject $date\n\t\t\t * @param string $message\n\t\t\t */\n\t\t\t    private function edit($log,$date,$message) {\n\t\t\t\t$logcontent = \"Time : \" . $date->format('H:i:s').\"\\r\\n\" . $message .\"\\r\\n\\r\\n\";\n\t\t\t\t$logcontent = $logcontent . file_get_contents($log);\n\t\t\t\tfile_put_contents($log, $logcontent);\n\t\t\t    }\n\t\t}\n?>\n"
  },
  {
    "path": "README.md",
    "content": "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!\n============================\n\nPDO Database Class\n============================\n\nA database class for PHP-MySQL which uses the PDO extension.\n\n## To use the class\n#### 1. Edit the database settings in the settings.ini.php\n### Note if PDO is loading slow change localhost to -> 127.0.0.1 !\n```\n[SQL]\nhost = 127.0.0.1\nuser = root\npassword = \ndbname = yourdatabase\n```\n#### 2. Require the class in your project\n```php\n<?php\nrequire(\"Db.class.php\");\n```\n#### 3. Create the instance \n```php\n<?php\n// The instance\n$db = new Db();\n```\n#### 4.  Logs - Modify the read/write rights of the root folder\n\nEverytime an exception is thrown by the database class a log file gets created or modified.\nThese logs are stored in the logs directory. Which means the database class needs write access for the logs folder.\nIf the files are on a webserver you'll have to modify the rights of the root folder otherwise you'll get a \"Permission denied\" error.\n\nThe log file is a simple plain text file with the current date('year-month-day') as filename.\n\n## Examples\nBelow some examples of the basic functions of the database class. I've included a SQL dump so you can easily test the database\nclass functions. \n#### The persons table \n| id | firstname | lastname | sex | age\n|:-----------:|:------------:|:------------:|:------------:|:------------:|\n| 1       |        John |     Doe    | M | 19\n| 2       |        Bob  |     Black    | M | 41\n| 3       |        Zoe  |     Chan    | F | 20\n| 4       |        Kona |     Khan    | M | 14\n| 5       |        Kader|     Khan    | M | 56\n\n#### Fetching everything from the table\n```php\n<?php\n// Fetch whole table\n$persons = $db->query(\"SELECT * FROM persons\");\n```\n#### Fetching with Bindings (ANTI-SQL-INJECTION):\nBinding parameters is the best way to prevent SQL injection. The class prepares your SQL query and binds the parameters\nafterwards.\n\nThere are three different ways to bind parameters.\n```php\n<?php\n// 1. Read friendly method  \n$db->bind(\"id\",\"1\");\n$db->bind(\"firstname\",\"John\");\n$person   =  $db->query(\"SELECT * FROM Persons WHERE firstname = :firstname AND id = :id\");\n\n// 2. Bind more parameters\n$db->bindMore(array(\"firstname\"=>\"John\",\"id\"=>\"1\"));\n$person   =  $db->query(\"SELECT * FROM Persons WHERE firstname = :firstname AND id = :id\"));\n\n// 3. Or just give the parameters to the method\n$person   =  $db->query(\"SELECT * FROM Persons WHERE firstname = :firstname AND id = :id\",array(\"firstname\"=>\"John\",\"id\"=>\"1\"));\n```\n\nMore about SQL injection prevention : http://indieteq.com/index/readmore/how-to-prevent-sql-injection-in-php\n\n#### Fetching Row:\nThis method always returns only 1 row.\n```php\n<?php\n// Fetch a row\n$ages     =  $db->row(\"SELECT * FROM Persons WHERE  id = :id\", array(\"id\"=>\"1\"));\n```\n##### Result\n| id | firstname | lastname | sex | age\n|:-----------:|:------------:|:------------:|:------------:|:------------:|\n| 1       |        John |     Doe    | M | 19\n#### Fetching Single Value:\nThis method returns only one single value of a record.\n```php\n<?php\n// Fetch one single value\n$db->bind(\"id\",\"3\");\n$firstname = $db->single(\"SELECT firstname FROM Persons WHERE id = :id\");\n```\n##### Result\n|firstname\n|:------------:\n| Zoe\n\n#### Using the like keyword\n```php\n<?php\n// Using Like \n// Notice the wildcard at the end of the value!!\n$like = $db->query(\"SELECT * FROM Persons WHERE Firstname LIKE :firstname \", array(\"firstname\"=>\"sekit%\"));\n```\n##### Result\n| id | firstname | lastname | sex | age\n|:-----------:|:------------:|:------------:|:------------:|:------------:|\n| 4       |        Sekito |     Khan | M | 19\n\n#### Fetching Column:\n```php\n<?php\n// Fetch a column\n$names    =  $db->column(\"SELECT Firstname FROM Persons\");\n```\n##### Result\n|firstname | \n|:-----------:\n|        John \n|        Bob  \n|        Zoe  \n|        Kona \n|        Kader\n### Delete / Update / Insert\nWhen executing the delete, update, or insert statement by using the query method the affected rows will be returned.\n```php\n<?php\n\n// Delete\n$delete   =  $db->query(\"DELETE FROM Persons WHERE Id = :id\", array(\"id\"=>\"1\"));\n\n// Update\n$update   =  $db->query(\"UPDATE Persons SET firstname = :f WHERE Id = :id\", array(\"f\"=>\"Jan\",\"id\"=>\"32\"));\n\n// Insert\n$insert   =  $db->query(\"INSERT INTO Persons(Firstname,Age) VALUES(:f,:age)\", array(\"f\"=>\"Vivek\",\"age\"=>\"20\"));\n\n// Do something with the data \nif($insert > 0 ) {\n  return 'Succesfully created a new person !';\n}\n\n```\n## Method parameters\nEvery method which executes a query has the optional parameter called bindings.\n\nThe <i>row</i> and the <i>query</i> method have a third optional parameter  which is the fetch style.\nThe default fetch style is <i>PDO::FETCH_ASSOC</i> which returns an associative array.\n\nHere an example :\n\n```php\n<?php\n  // Fetch style as third parameter\n  $person_num =     $db->row(\"SELECT * FROM Persons WHERE id = :id\", array(\"id\"=>\"1\"), PDO::FETCH_NUM);\n\n  print_r($person_num);\n  // Array ( [0] => 1 [1] => Johny [2] => Doe [3] => M [4] => 19 )\n    \n```\nMore info about the PDO fetchstyle : http://php.net/manual/en/pdostatement.fetch.php\n\n\nEasyCRUD\n============================\nThe easyCRUD is a class which you can use to easily execute basic SQL operations like(insert, update, select, delete) on your database. \nIt uses the database class I've created to execute the SQL queries.\n\nActually it's just a little ORM class.\n\n## How to use easyCRUD\n#### 1. First, create a new class. Then require the easyCRUD class.\n#### 2. Extend your class to the base class Crud and add the following fields to the class.\n#### Example class :\n```php\n<?php\nrequire_once(\"easyCRUD.class.php\");\n \nclass YourClass  Extends Crud {\n \n  # The table you want to perform the database actions on\n  protected $table = 'persons';\n\n  # Primary Key of the table\n  protected $pk  = 'id';\n  \n}\n```\n\n## EasyCRUD in action.\n\n#### Creating a new person\n```php\n<?php\n// First we\"ll have create the instance of the class\n$person = new person();\n \n// Create new person\n$person->Firstname  = \"Kona\";\n$person->Age        = \"20\";\n$person->Sex        = \"F\";\n$created            = $person->Create();\n \n//  Or give the bindings to the constructor\n$person  = new person(array(\"Firstname\"=>\"Kona\",\"age\"=>\"20\",\"sex\"=>\"F\"));\n$created = $person->Create();\n \n// SQL Equivalent\n\"INSERT INTO persons (Firstname,Age,Sex) VALUES ('Kona','20','F')\"\n```\n#### Deleting a person\n```php\n<?php\n// Delete person\n$person->Id  = \"17\";\n$deleted     = $person->Delete();\n \n// Shorthand method, give id as parameter\n$deleted     = $person->Delete(17);\n \n// SQL Equivalent\n\"DELETE FROM persons WHERE Id = 17 LIMIT 1\"\n```\n#### Saving person's data\n```php\n<?php\n// Update personal data\n$person->Firstname = \"John\";\n$person->Age  = \"20\";\n$person->Sex = \"F\";\n$person->Id  = \"4\"; \n// Returns affected rows\n$saved = $person->Save();\n \n//  Or give the bindings to the constructor\n$person = new person(array(\"Firstname\"=>\"John\",\"age\"=>\"20\",\"sex\"=>\"F\",\"Id\"=>\"4\"));\n$saved = $person->Save();\n \n// SQL Equivalent\n\"UPDATE persons SET Firstname = 'John',Age = 20, Sex = 'F' WHERE Id= 4\"\n```\n#### Finding a person\n```php\n<?php\n// Find person\n$person->Id = \"1\";\n$person->find();\n\necho $person->Firstname;\n// Johny\n \n// Shorthand method, give id as parameter\n$person->find(1); \n \n// SQL Equivalent\n\"SELECT * FROM persons WHERE Id = 1\"\n```\n#### Getting all the persons\n```php\n<?php\n// Finding all person\n$persons = $person->all(); \n \n// SQL Equivalent\n\"SELECT * FROM persons \n```\n\n## Copyright and license\n#### Code released under Beerware\n\n"
  },
  {
    "path": "SQL dump/testdb.sql",
    "content": "/*\nNavicat MySQL Data Transfer\n\nSource Server         : localhost_3306\nSource Server Version : 50527\nSource Host           : localhost:3306\nSource Database       : testdb\n\nTarget Server Type    : MYSQL\nTarget Server Version : 50527\nFile Encoding         : 65001\n\nDate: 2012-11-12 14:07:39\n*/\n\nSET FOREIGN_KEY_CHECKS=0;\n\n-- ----------------------------\n-- Table structure for `persons`\n-- ----------------------------\nDROP TABLE IF EXISTS `persons`;\nCREATE TABLE `persons` (\n  `Id` int(11) NOT NULL AUTO_INCREMENT,\n  `Firstname` varchar(32) DEFAULT NULL,\n  `Lastname` varchar(32) DEFAULT NULL,\n  `Sex` char(1) DEFAULT NULL,\n  `Age` tinyint(3) DEFAULT NULL,\n  PRIMARY KEY (`Id`)\n) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;\n\n-- ----------------------------\n-- Records of persons\n-- ----------------------------\nINSERT INTO `persons` VALUES ('1', 'John', 'Doe', 'M', '19');\nINSERT INTO `persons` VALUES ('2', 'Bob', 'Black', 'M', '40');\nINSERT INTO `persons` VALUES ('3', 'Zoe', 'Chan', 'F', '21');\nINSERT INTO `persons` VALUES ('4', 'Sekito', 'Khan', 'M', '19');\nINSERT INTO `persons` VALUES ('5', 'Kader', 'Khan', 'M', '56');\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"indieteq/indieteq-php-my-sql-pdo-database-class\",\n    \"description\": \"A database class for MySQL with PDO\",\n    \"type\": \"library\",\n    \"keywords\": [ \"mysql\", \"pdo\", \"php\", \"beer\", \"free\" ],\n    \"homepage\": \"https://github.com/wickyaswal/indieteq-php-my-sql-pdo-database-class\",\n    \"license\": \"Beerware\",\n    \"authors\": [\n        { \"name\": \"wicky\", \"email\": \"info@wickyaswal.com\" }\n    ],\n    \"require\": {\n         \"php\": \">=5.3.0\"\n    }\n}\n"
  },
  {
    "path": "easyCRUD/Person.class.php",
    "content": "<?php \n\trequire_once(\"easyCRUD.class.php\");\n\n\tclass Person  Extends Crud {\n\t\t\n\t\t\t# Your Table name \n\t\t\tprotected $table = 'persons';\n\t\t\t\n\t\t\t# Primary Key of the Table\n\t\t\tprotected $pk\t = 'id';\n\t}\n\n?>"
  },
  {
    "path": "easyCRUD/easyCRUD.class.php",
    "content": "<?php \n/**\n* Easy Crud  -  This class kinda works like ORM. Just created for fun :) \n*\n* @author\t\tAuthor: Vivek Wicky Aswal. (https://twitter.com/#!/VivekWickyAswal)\n* @version      0.1a\n*/\nrequire_once(__DIR__ . '/../Db.class.php');\nclass Crud {\n\n\tprivate $db;\n\n\tpublic $variables;\n\n\tpublic function __construct($data = array()) {\n\t\t$this->db =  new DB();\t\n\t\t$this->variables  = $data;\n\t}\n\n\tpublic function __set($name,$value){\n\t\tif(strtolower($name) === $this->pk) {\n\t\t\t$this->variables[$this->pk] = $value;\n\t\t}\n\t\telse {\n\t\t\t$this->variables[$name] = $value;\n\t\t}\n\t}\n\n\tpublic function __get($name)\n\t{\t\n\t\tif(is_array($this->variables)) {\n\t\t\tif(array_key_exists($name,$this->variables)) {\n\t\t\t\treturn $this->variables[$name];\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\tpublic function save($id = \"0\") {\n\t\t$this->variables[$this->pk] = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];\n\n\t\t$fieldsvals = '';\n\t\t$columns = array_keys($this->variables);\n\n\t\tforeach($columns as $column)\n\t\t{\n\t\t\tif($column !== $this->pk)\n\t\t\t$fieldsvals .= $column . \" = :\". $column . \",\";\n\t\t}\n\n\t\t$fieldsvals = substr_replace($fieldsvals , '', -1);\n\n\t\tif(count($columns) > 1 ) {\n\n\t\t\t$sql = \"UPDATE \" . $this->table .  \" SET \" . $fieldsvals . \" WHERE \" . $this->pk . \"= :\" . $this->pk;\n\t\t\tif($id === \"0\" && $this->variables[$this->pk] === \"0\") { \n\t\t\t\tunset($this->variables[$this->pk]);\n\t\t\t\t$sql = \"UPDATE \" . $this->table .  \" SET \" . $fieldsvals;\n\t\t\t}\n\n\t\t\treturn $this->exec($sql);\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tpublic function create() { \n\t\t$bindings   \t= $this->variables;\n\n\t\tif(!empty($bindings)) {\n\t\t\t$fields     =  array_keys($bindings);\n\t\t\t$fieldsvals =  array(implode(\",\",$fields),\":\" . implode(\",:\",$fields));\n\t\t\t$sql \t\t= \"INSERT INTO \".$this->table.\" (\".$fieldsvals[0].\") VALUES (\".$fieldsvals[1].\")\";\n\t\t}\n\t\telse {\n\t\t\t$sql \t\t= \"INSERT INTO \".$this->table.\" () VALUES ()\";\n\t\t}\n\n\t\treturn $this->exec($sql);\n\t}\n\n\tpublic function delete($id = \"\") {\n\t\t$id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];\n\n\t\tif(!empty($id)) {\n\t\t\t$sql = \"DELETE FROM \" . $this->table . \" WHERE \" . $this->pk . \"= :\" . $this->pk. \" LIMIT 1\" ;\n\t\t}\n\n\t\treturn $this->exec($sql, array($this->pk=>$id));\n\t}\n\n\tpublic function find($id = \"\") {\n\t\t$id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk];\n\n\t\tif(!empty($id)) {\n\t\t\t$sql = \"SELECT * FROM \" . $this->table .\" WHERE \" . $this->pk . \"= :\" . $this->pk . \" LIMIT 1\";\t\n\t\t\t\n\t\t\t$result = $this->db->row($sql, array($this->pk=>$id));\n\t\t\t$this->variables = ($result != false) ? $result : null;\n\t\t}\n\t}\n\t/**\n\t* @param array $fields.\n\t* @param array $sort.\n\t* @return array of Collection.\n\t* Example: $user = new User;\n\t* $found_user_array = $user->search(array('sex' => 'Male', 'age' => '18'), array('dob' => 'DESC'));\n\t* // Will produce: SELECT * FROM {$this->table_name} WHERE sex = :sex AND age = :age ORDER BY dob DESC;\n\t* // And rest is binding those params with the Query. Which will return an array.\n\t* // Now we can use for each on $found_user_array.\n\t* Other functionalities ex: Support for LIKE, >, <, >=, <= ... Are not yet supported.\n\t*/\n\tpublic function search($fields = array(), $sort = array()) {\n\t\t$bindings = empty($fields) ? $this->variables : $fields;\n\n\t\t$sql = \"SELECT * FROM \" . $this->table;\n\n\t\tif (!empty($bindings)) {\n\t\t\t$fieldsvals = array();\n\t\t\t$columns = array_keys($bindings);\n\t\t\tforeach($columns as $column) {\n\t\t\t\t$fieldsvals [] = $column . \" = :\". $column;\n\t\t\t}\n\t\t\t$sql .= \" WHERE \" . implode(\" AND \", $fieldsvals);\n\t\t}\n\t\t\n\t\tif (!empty($sort)) {\n\t\t\t$sortvals = array();\n\t\t\tforeach ($sort as $key => $value) {\n\t\t\t\t$sortvals[] = $key . \" \" . $value;\n\t\t\t}\n\t\t\t$sql .= \" ORDER BY \" . implode(\", \", $sortvals);\n\t\t}\n\t\treturn $this->exec($sql);\n\t}\n\n\tpublic function all(){\n\t\treturn $this->db->query(\"SELECT * FROM \" . $this->table);\n\t}\n\t\n\tpublic function min($field)  {\n\t\tif($field)\n\t\treturn $this->db->single(\"SELECT min(\" . $field . \")\" . \" FROM \" . $this->table);\n\t}\n\n\tpublic function max($field)  {\n\t\tif($field)\n\t\treturn $this->db->single(\"SELECT max(\" . $field . \")\" . \" FROM \" . $this->table);\n\t}\n\n\tpublic function avg($field)  {\n\t\tif($field)\n\t\treturn $this->db->single(\"SELECT avg(\" . $field . \")\" . \" FROM \" . $this->table);\n\t}\n\n\tpublic function sum($field)  {\n\t\tif($field)\n\t\treturn $this->db->single(\"SELECT sum(\" . $field . \")\" . \" FROM \" . $this->table);\n\t}\n\n\tpublic function count($field)  {\n\t\tif($field)\n\t\treturn $this->db->single(\"SELECT count(\" . $field . \")\" . \" FROM \" . $this->table);\n\t}\t\n\t\n\n\tprivate function exec($sql, $array = null) {\n\t\t\n\t\tif($array !== null) {\n\t\t\t// Get result with the DB object\n\t\t\t$result =  $this->db->query($sql, $array);\t\n\t\t}\n\t\telse {\n\t\t\t// Get result with the DB object\n\t\t\t$result =  $this->db->query($sql, $this->variables);\t\n\t\t}\n\t\t\n\t\t// Empty bindings\n\t\t$this->variables = array();\n\n\t\treturn $result;\n\t}\n\n}\n?>\n"
  },
  {
    "path": "easyCRUD/index.php",
    "content": "<?php \n// Require the person class file\n   require(\"Person.class.php\");\n\t\n// Instantiate the person class\n   $person  = new Person();\n\n// Create new person\n   $person->Firstname = \"Kona\";\n   $person->Age  = \"20\";\n   $person->Sex = \"F\";\n   $creation = $person->Create();\n\n// Update Person Info\n   $person->id = \"4\";\t\n   $person->Age = \"32\";\n   $saved = $person->Save(); \n\n// Find person\n   $person->id = \"4\";\t\t\n   $person->Find();\n\n   d($person->Firstname, \"Person->Firstname\");\n   d($person->Age, \"Person->Age\");\n\n// Delete person\n   $person->id = \"17\";\t\n   $delete = $person->Delete();\n\n // Get all persons\n   $persons = $person->all();  \n\n   // Aggregates methods \n   d($person->max('age'), \"Max person age\");\n   d($person->min('age'), \"Min person age\");\n   d($person->sum('age'), \"Sum persons age\");\n   d($person->avg('age'), \"Average persons age\");\n   d($person->count('id'), \"Count persons\");\n\n   function d($v, $t = \"\") \n   {\n      echo '<pre>';\n      echo '<h1>' . $t. '</h1>';\n      var_dump($v);\n      echo '</pre>';\n   }\n\n?>\n"
  },
  {
    "path": "index.php",
    "content": "<?php\n\trequire(\"Db.class.php\");\n\n\t// Creates the instance\n\t$db = new Db();\n\t\t\n\t// 3 ways to bind parameters :\t\t\n\t\n\t// 1. Read friendly method\t\n\t$db->bind(\"firstname\",\"John\");\n\t$db->bind(\"age\",\"19\");\n\n\t// 2. Bind more parameters\n\t$db->bindMore(array(\"firstname\"=>\"John\",\"age\"=>\"19\"));\t\t\n\n\t// 3. Or just give the parameters to the method\n\t$db->query(\"SELECT * FROM Persons WHERE firstname = :firstname AND age = :age\", array(\"firstname\"=>\"John\",\"age\"=>\"19\"));\n\n\t//  Fetching data\n\t$person \t =     $db->query(\"SELECT * FROM Persons\");\n\n\t// If you want another fetchmode just give it as parameter\n\t$persons_num     =     $db->query(\"SELECT * FROM Persons\", null, PDO::FETCH_NUM);\n\t\n\t// Fetching single value\n\t$firstname\t =     $db->single(\"SELECT firstname FROM Persons WHERE Id = :id \", array('id' => '3' ) );\n\t\n\t// Single Row\n\t$id_age \t =     $db->row(\"SELECT Id, Age FROM Persons WHERE firstname = :f\", array(\"f\"=>\"Zoe\"));\n\t\t\n\t// Single Row with numeric index\n\t$id_age_num      =     $db->row(\"SELECT Id, Age FROM Persons WHERE firstname = :f\", array(\"f\"=>\"Zoe\"),PDO::FETCH_NUM);\n\t\n\t// Column, numeric index\n\t$ages  \t\t =     $db->column(\"SELECT age FROM Persons\");\n\n\t// The following statements will return the affected rows\n\t\n\t// Update statement\n\t$update\t\t =  $db->query(\"UPDATE Persons SET firstname = :f WHERE Id = :id\",array(\"f\"=>\"Johny\",\"id\"=>\"1\")); \n\t\n\t// Insert statement\n//\t$insert\t \t =  $db->query(\"INSERT INTO Persons(Firstname,Age) \tVALUES(:f,:age)\",array(\"f\"=>\"Vivek\",\"age\"=>\"20\"));\n\t\n\t// Delete statement\n//\t$delete\t \t =  $db->query(\"DELETE FROM Persons WHERE Id = :id\",array(\"id\"=>\"6\")); \n\t\n\tfunction d($v, $t = \"\") \n\t{\n\t\techo '<pre>';\n\t\techo '<h1>' . $t. '</h1>';\n\t\tvar_dump($v);\n\t\techo '</pre>';\n\t}\n\t//d($person, \"All persons\");\n\td($id_age, \"Single Row, Id and Age\");\n\td($firstname, \"Fetch Single value, The firstname\");\n\td($ages, \"Fetch Column, Numeric Index\");\n\n?>\n"
  },
  {
    "path": "settings.ini.php",
    "content": ";<?php return; ?>\n[SQL]\nhost = localhost\nuser = root\npassword = \ndbname = testdb\n"
  }
]