From fda5f14b8fefad0a80d01b694ff5621fc0976894 Mon Sep 17 00:00:00 2001 From: Indieteq Date: Wed, 17 Oct 2012 21:38:56 +0200 Subject: The database files --- Db.class.php | 242 ++++++++++++++++++++++++++++++++++++++++++++ Log.class.php | 70 +++++++++++++ easyCRUD/Person.class.php | 13 +++ easyCRUD/easyCRUD.class.php | 96 ++++++++++++++++++ easyCRUD/index.php | 39 +++++++ settings.ini.php | 5 + 6 files changed, 465 insertions(+) create mode 100644 Db.class.php create mode 100644 Log.class.php create mode 100644 easyCRUD/Person.class.php create mode 100644 easyCRUD/easyCRUD.class.php create mode 100644 easyCRUD/index.php create mode 100644 settings.ini.php diff --git a/Db.class.php b/Db.class.php new file mode 100644 index 0000000..0798c72 --- /dev/null +++ b/Db.class.php @@ -0,0 +1,242 @@ +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 + $this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"]); + + # 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(); + } + } + /** + * 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) + { + $parameters = explode("\x7F",$param); + $this->sQuery->bindParam($parameters[0],$parameters[1]); + } + } + + # Execute SQL + $this->succes = $this->sQuery->execute(); + } + catch(PDOException $e) + { + # Write into log and display Exception + echo $this->ExceptionLog($e->getMessage(),$this->sQuery->queryString); + 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 . "\x7F" . $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 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($query); + + $this->Init($query,$params); + + if (stripos($query, 'select') === 0){ + return $this->sQuery->fetchAll($fetchmode); + } + elseif (stripos($query, 'insert') === 0 || stripos($query, 'update') === 0 || stripos($query, 'delete') === 0) { + return $this->sQuery->rowCount(); + } + else { + return NULL; + } + } + /** + * 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); + return $this->sQuery->fetch($fetchmode); + } + /** + * 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); + return $this->sQuery->fetchColumn(); + } + /** + * 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; + } + } +?> \ No newline at end of file diff --git a/Log.class.php b/Log.class.php new file mode 100644 index 0000000..58e5672 --- /dev/null +++ b/Log.class.php @@ -0,0 +1,70 @@ +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, 'w') 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) // Check on true, Otherwise we would have a never-ending loop :S + { + $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); + } + } +?> \ No newline at end of file diff --git a/easyCRUD/Person.class.php b/easyCRUD/Person.class.php new file mode 100644 index 0000000..131b6b3 --- /dev/null +++ b/easyCRUD/Person.class.php @@ -0,0 +1,13 @@ + \ No newline at end of file diff --git a/easyCRUD/easyCRUD.class.php b/easyCRUD/easyCRUD.class.php new file mode 100644 index 0000000..3e4c647 --- /dev/null +++ b/easyCRUD/easyCRUD.class.php @@ -0,0 +1,96 @@ +variables[$name] = $value; + } + + public function __get($name) + { + if(array_key_exists($name,$this->variables)) { + return $this->variables[$name]; + } + + $trace = debug_backtrace(); + trigger_error( + 'Undefined property via __get(): ' . $name . + ' in ' . $trace[0]['file'] . + ' on line ' . $trace[0]['line'], + E_USER_NOTICE); + return null; + } + + public function __construct($data = array()) { + $this->db = new DB(); + $this->variables = $data; + } + + 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; + return $this->db->query($sql,$this->variables); + } + } + + 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->db->query($sql,$bindings); + } + + 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->db->query($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"; + $this->variables = $this->db->row($sql,array($this->pk=>$id)); + } + } + + public function all(){ + return $this->db->query("SELECT * FROM " . $this->table); + } +} +?> \ No newline at end of file diff --git a/easyCRUD/index.php b/easyCRUD/index.php new file mode 100644 index 0000000..23c4e8b --- /dev/null +++ b/easyCRUD/index.php @@ -0,0 +1,39 @@ +"kona","Age"=>"20","Sex"=>"F")); + //$person = new Person(array("id"=>"67")); + +// Create new person +// $person->Firstname = "Kona"; +// $person->Age = "20"; +// $person->Sex = "F"; +// $creation = $person->Create(); + + //var_dump($creation); + +// Update Person Info +// $person->id = "4"; +// $person->Age = "32"; +// $saved = $person->Save(); + +// var_dump($saved); + +// Find person + //$person->id = "4"; + //$person->Find(); + +// echo $person->Firstname; +// echo $person->Age; + +// Delete person +// $person->id = "17"; + $delete = $person->Delete(); + var_dump($delete); + + // Get all persons + $persons = $person->all(); + + +?> \ No newline at end of file diff --git a/settings.ini.php b/settings.ini.php new file mode 100644 index 0000000..d0472a7 --- /dev/null +++ b/settings.ini.php @@ -0,0 +1,5 @@ +[SQL] +host = localhost +user = root +password = +dbname = ultim \ No newline at end of file -- cgit v1.1