From 12ba0ce7ea8e98ae0d1eeffd88b2522e2b079293 Mon Sep 17 00:00:00 2001 From: log2ks Date: Fri, 3 Jan 2014 09:51:18 +0800 Subject: [PATCH 01/39] Update class.MySQL.php Use a port option --- class.MySQL.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 13d86f6..878d78f 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -44,11 +44,11 @@ class MySQL { * Class Constructor * * *******************/ - function __construct($database, $username, $password, $hostname='localhost'){ + function __construct($database, $username, $password, $hostname='localhost', $port=3306){ $this->database = $database; $this->username = $username; $this->password = $password; - $this->hostname = $hostname; + $this->hostname = $hostname.':'.$port; $this->Connect(); } From 27f5c293299982f54414cff1b49ba3ade695d585 Mon Sep 17 00:00:00 2001 From: Tom Witkowski Date: Tue, 15 Apr 2014 14:31:10 +0200 Subject: [PATCH 02/39] [ISSUE #35] Update class.MySQL.php syntax [ISSUE #37] better data-security with given variable-types --- class.MySQL.php | 497 ++++++++++++++++++++++++++---------------------- 1 file changed, 271 insertions(+), 226 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 878d78f..b6e276d 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -23,20 +23,20 @@ class MySQL { // Base variables - var $lastError; // Holds the last error - var $lastQuery; // Holds the last query - var $result; // Holds the MySQL query result - var $records; // Holds the total number of records returned - var $affected; // Holds the total number of records affected - var $rawResults; // Holds raw 'arrayed' results - var $arrayedResult; // Holds an array of the result + var $lastError; // Holds the last error + var $lastQuery; // Holds the last query + var $result; // Holds the MySQL query result + var $records; // Holds the total number of records returned + var $affected; // Holds the total number of records affected + var $rawResults; // Holds raw 'arrayed' results + var $arrayedResult; // Holds an array of the result - var $hostname; // MySQL Hostname - var $username; // MySQL Username - var $password; // MySQL Password - var $database; // MySQL Database + var $hostname; // MySQL Hostname + var $username; // MySQL Username + var $password; // MySQL Password + var $database; // MySQL Database - var $databaseLink; // Database Connection Link + var $databaseLink; // Database Connection Link @@ -95,234 +95,279 @@ private function UseDB(){ // Performs a 'mysql_real_escape_string' on the entire array/string - private function SecureData($data){ + private function SecureData($data, $types){ if(is_array($data)){ + $i = 0; foreach($data as $key=>$val){ if(!is_array($data[$key])){ + $data[$key] = $this->CleanData($data[$key], $types[$i]); $data[$key] = mysql_real_escape_string($data[$key], $this->databaseLink); + $i++; } } }else{ + $data = $this->CleanData($data, $types); $data = mysql_real_escape_string($data, $this->databaseLink); } return $data; } - - - - /* ****************** - * Public Functions * - * ******************/ - - // Executes MySQL query - function ExecuteSQL($query){ - $this->lastQuery = $query; - if($this->result = mysql_query($query, $this->databaseLink)){ - $this->records = @mysql_num_rows($this->result); - $this->affected = @mysql_affected_rows($this->databaseLink); - - if($this->records > 0){ - $this->ArrayResults(); - return $this->arrayedResult; - }else{ - return true; - } - - }else{ - $this->lastError = mysql_error($this->databaseLink); - return false; - } - } - - - // Adds a record to the database based on the array key names - function Insert($vars, $table, $exclude = ''){ - - // Catch Exclusions - if($exclude == ''){ - $exclude = array(); - } - - array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one - - // Prepare Variables - $vars = $this->SecureData($vars); - - $query = "INSERT INTO `{$table}` SET "; - foreach($vars as $key=>$value){ - if(in_array($key, $exclude)){ - continue; - } - //$query .= '`' . $key . '` = "' . $value . '", '; - $query .= "`{$key}` = '{$value}', "; - } - - $query = substr($query, 0, -2); - - return $this->ExecuteSQL($query); - } - - // Deletes a record from the database - function Delete($table, $where='', $limit='', $like=false){ - $query = "DELETE FROM `{$table}` WHERE "; - if(is_array($where) && $where != ''){ - // Prepare Variables - $where = $this->SecureData($where); - - foreach($where as $key=>$value){ - if($like){ - //$query .= '`' . $key . '` LIKE "%' . $value . '%" AND '; - $query .= "`{$key}` LIKE '%{$value}%' AND "; - }else{ - //$query .= '`' . $key . '` = "' . $value . '" AND '; - $query .= "`{$key}` = '{$value}' AND "; - } - } - - $query = substr($query, 0, -5); - } - - if($limit != ''){ - $query .= ' LIMIT ' . $limit; - } - - return $this->ExecuteSQL($query); - } - - - // Gets a single row from $from where $where is true - function Select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*'){ - // Catch Exceptions - if(trim($from) == ''){ - return false; - } - - $query = "SELECT {$cols} FROM `{$from}` WHERE "; - - if(is_array($where) && $where != ''){ - // Prepare Variables - $where = $this->SecureData($where); - - foreach($where as $key=>$value){ - if($like){ - //$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' '; - $query .= "`{$key}` LIKE '%{$value}%' {$operand} "; - }else{ - //$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' '; - $query .= "`{$key}` = '{$value}' {$operand} "; - } - } - - $query = substr($query, 0, -(strlen($operand)+2)); + + // clean the variable with given types + // possible types: none, str, int, float, bool, datetime, ts2dt (given timestamp convert to mysql datetime) + // bonus types: hexcolor, email + private function CleanData($data, $type = ''){ + switch($type) { + case 'none': + $data = $data; + break; + case 'str': + $data = settype( $data, 'string'); + break; + case 'int': + $data = settype( $data, 'integer'); + break; + case 'float': + $data = settype( $data, 'float'); + break; + case 'bool': + $data = settype( $data, 'boolean'); + break; + // Y-m-d H:i:s + // 2014-01-01 12:30:30 + case 'datetime': + $data = trim( $data ); + $data = preg_replace('/[^\d\-: ]/i', '', $data); + preg_match( '/^([\d]{4}-[\d]{2}-[\d]{2} [\d]{2}:[\d]{2}:[\d]{2})$/', $data, $matches ); + $data = $matches[1]; + break; + case 'ts2dt': + $data = settype( $data, 'integer'); + $data = date('Y-m-d H:i:s', $data); + break; - }else{ - $query = substr($query, 0, -6); - } - - if($orderBy != ''){ - $query .= ' ORDER BY ' . $orderBy; - } - - if($limit != ''){ - $query .= ' LIMIT ' . $limit; - } - - return $this->ExecuteSQL($query); - - } - - // Updates a record in the database based on WHERE - function Update($table, $set, $where, $exclude = ''){ - // Catch Exceptions - if(trim($table) == '' || !is_array($set) || !is_array($where)){ - return false; - } - if($exclude == ''){ - $exclude = array(); - } - - array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one - - $set = $this->SecureData($set); - $where = $this->SecureData($where); - - // SET - - $query = "UPDATE `{$table}` SET "; - - foreach($set as $key=>$value){ - if(in_array($key, $exclude)){ - continue; - } - $query .= "`{$key}` = '{$value}', "; - } - - $query = substr($query, 0, -2); - - // WHERE - - $query .= ' WHERE '; - - foreach($where as $key=>$value){ - $query .= "`{$key}` = '{$value}' AND "; - } - - $query = substr($query, 0, -5); - - return $this->ExecuteSQL($query); - } - - // 'Arrays' a single result - function ArrayResult(){ - $this->arrayedResult = mysql_fetch_assoc($this->result) or die (mysql_error($this->databaseLink)); - return $this->arrayedResult; - } + // bonus types + case 'hexcolor': + preg_match( '/(#[0-9abcdef]{6})/i', $data, $matches ); + $data = $matches[1]; + break; + case 'email': + $data = filter_var($data, FILTER_VALIDATE_EMAIL); + break; + default: + $data = ''; + break; + } + return $data; + } - // 'Arrays' multiple result - function ArrayResults(){ - - if($this->records == 1){ - return $this->ArrayResult(); - } - - $this->arrayedResult = array(); - while ($data = mysql_fetch_assoc($this->result)){ - $this->arrayedResult[] = $data; - } - return $this->arrayedResult; - } - - // 'Arrays' multiple results with a key - function ArrayResultsWithKey($key='id'){ - if(isset($this->arrayedResult)){ - unset($this->arrayedResult); - } - $this->arrayedResult = array(); - while($row = mysql_fetch_assoc($this->result)){ - foreach($row as $theKey => $theValue){ - $this->arrayedResult[$row[$key]][$theKey] = $theValue; - } - } - return $this->arrayedResult; - } - // Returns last insert ID - function LastInsertID(){ - return mysql_insert_id(); - } - // Return number of rows - function CountRows($from, $where=''){ - $result = $this->Select($from, $where, '', '', false, 'AND','count(*)'); - return $result["count(*)"]; - } + /* ****************** + * Public Functions * + * ******************/ - // Closes the connections - function CloseConnection(){ - if($this->databaseLink){ - mysql_close($this->databaseLink); - } - } -} + // Executes MySQL query + public function executeSQL($query){ + $this->lastQuery = $query; + if($this->result = mysql_query($query, $this->databaseLink)){ + $this->records = @mysql_num_rows($this->result); + $this->affected = @mysql_affected_rows($this->databaseLink); + + if($this->records > 0){ + $this->arrayResults(); + return $this->arrayedResult; + }else{ + return true; + } + + }else{ + $this->lastError = mysql_error($this->databaseLink); + return false; + } + } + + + // Adds a record to the database based on the array key names + public function insert($table, $vars, $exclude = '', $datatypes){ + + // Catch Exclusions + if($exclude == ''){ + $exclude = array(); + } + + array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one + + // Prepare Variables + $vars = $this->SecureData($vars, $datatypes); + + $query = "INSERT INTO `{$table}` SET "; + foreach($vars as $key=>$value){ + if(in_array($key, $exclude)){ + continue; + } + $query .= "`{$key}` = '{$value}', "; + } + + $query = trim($query, ', '); + + return $this->executeSQL($query); + } + + // Deletes a record from the database + public function delete($table, $where='', $limit='', $like=false, $wheretypes){ + $query = "DELETE FROM `{$table}` WHERE "; + if(is_array($where) && $where != ''){ + // Prepare Variables + $where = $this->SecureData($where, $wheretypes); + + foreach($where as $key=>$value){ + if($like){ + $query .= "`{$key}` LIKE '%{$value}%' AND "; + }else{ + $query .= "`{$key}` = '{$value}' AND "; + } + } + + $query = substr($query, 0, -5); + } + + if($limit != ''){ + $query .= ' LIMIT ' . $limit; + } + + return $this->executeSQL($query); + } + + + // Gets a single row from $from where $where is true + public function select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*', $wheretypes){ + // Catch Exceptions + if(trim($from) == ''){ + return false; + } + + $query = "SELECT {$cols} FROM `{$from}` WHERE "; + + if(is_array($where) && $where != ''){ + // Prepare Variables + $where = $this->SecureData($where, $wheretypes); + + foreach($where as $key=>$value){ + if($like){ + $query .= "`{$key}` LIKE '%{$value}%' {$operand} "; + }else{ + $query .= "`{$key}` = '{$value}' {$operand} "; + } + } + + $query = substr($query, 0, -(strlen($operand)+2)); + + }else{ + $query = substr($query, 0, -6); + } + + if($orderBy != ''){ + $query .= ' ORDER BY ' . $orderBy; + } + + if($limit != ''){ + $query .= ' LIMIT ' . $limit; + } + + return $this->executeSQL($query); + + } + + // Updates a record in the database based on WHERE + public function update($table, $set, $where, $exclude = '', $datatypes, $wheretypes){ + // Catch Exceptions + if(trim($table) == '' || !is_array($set) || !is_array($where)){ + return false; + } + if($exclude == ''){ + $exclude = array(); + } + + array_push($exclude, 'MAX_FILE_SIZE'); // Automatically exclude this one + + $set = $this->SecureData($set, $datatypes); + $where = $this->SecureData($where,$wheretypes); + + // SET + + $query = "UPDATE `{$table}` SET "; + + foreach($set as $key=>$value){ + if(in_array($key, $exclude)){ + continue; + } + $query .= "`{$key}` = '{$value}', "; + } + + $query = substr($query, 0, -2); + + // WHERE + + $query .= ' WHERE '; + + foreach($where as $key=>$value){ + $query .= "`{$key}` = '{$value}' AND "; + } + + $query = substr($query, 0, -5); + + return $this->executeSQL($query); + } + + // 'Arrays' a single result + public function arrayResult(){ + $this->arrayedResult = mysql_fetch_assoc($this->result) or die (mysql_error($this->databaseLink)); + return $this->arrayedResult; + } + + // 'Arrays' multiple result + public function arrayResults(){ + + if($this->records == 1){ + return $this->arrayResult(); + } + + $this->arrayedResult = array(); + while ($data = mysql_fetch_assoc($this->result)){ + $this->arrayedResult[] = $data; + } + return $this->arrayedResult; + } + + // 'Arrays' multiple results with a key + public function arrayResultsWithKey($key='id'){ + if(isset($this->arrayedResult)){ + unset($this->arrayedResult); + } + $this->arrayedResult = array(); + while($row = mysql_fetch_assoc($this->result)){ + foreach($row as $theKey => $theValue){ + $this->arrayedResult[$row[$key]][$theKey] = $theValue; + } + } + return $this->arrayedResult; + } + + // Returns last insert ID + public function lastInsertID(){ + return mysql_insert_id(); + } + + // Return number of rows + public function countRows($from, $where=''){ + $result = $this->select($from, $where, '', '', false, 'AND','count(*)'); + return $result["count(*)"]; + } -?> + // Closes the connections + public function closeConnection(){ + if($this->databaseLink){ + mysql_close($this->databaseLink); + } + } +} \ No newline at end of file From 60ee04a229e3e9161fb1a81afba055b4f6e20a1f Mon Sep 17 00:00:00 2001 From: Lars Borchert Date: Sat, 19 Apr 2014 21:35:06 +0200 Subject: [PATCH 03/39] fix issue #40 and add full type names like 'string' and 'integer' --- class.MySQL.php | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index b6e276d..c4da2c2 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -121,16 +121,19 @@ private function CleanData($data, $type = ''){ $data = $data; break; case 'str': - $data = settype( $data, 'string'); + case 'string': + settype( $data, 'string'); break; case 'int': - $data = settype( $data, 'integer'); + case 'integer': + settype( $data, 'integer'); break; case 'float': - $data = settype( $data, 'float'); + settype( $data, 'float'); break; case 'bool': - $data = settype( $data, 'boolean'); + case 'boolean': + settype( $data, 'boolean'); break; // Y-m-d H:i:s // 2014-01-01 12:30:30 @@ -141,7 +144,7 @@ private function CleanData($data, $type = ''){ $data = $matches[1]; break; case 'ts2dt': - $data = settype( $data, 'integer'); + settype( $data, 'integer'); $data = date('Y-m-d H:i:s', $data); break; From 3c6fe9de1d58f14ecc5efecaab5fe7102905a5d4 Mon Sep 17 00:00:00 2001 From: Argosback Date: Sat, 26 Apr 2014 22:02:24 -0500 Subject: [PATCH 04/39] query 'SET NAMES utf8' error: mysql_num_rows() expects parameter 1 to be resource --- class.MySQL.php | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index b6e276d..be170ae 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -168,10 +168,15 @@ private function CleanData($data, $type = ''){ // Executes MySQL query public function executeSQL($query){ - $this->lastQuery = $query; - if($this->result = mysql_query($query, $this->databaseLink)){ - $this->records = @mysql_num_rows($this->result); - $this->affected = @mysql_affected_rows($this->databaseLink); + $this->lastQuery = $query; + if($this->result = mysql_query($query, $this->databaseLink)){ + if (gettype($this->result) === 'resource') { + $this->records = @mysql_num_rows($this->result); + $this->affected = @mysql_affected_rows($this->databaseLink); + } else { + $this->records = 0; + $this->affected = 0; + } if($this->records > 0){ $this->arrayResults(); From 204358d452ae1357b8ab9335fe832d24553cc29e Mon Sep 17 00:00:00 2001 From: Jack Cherng Date: Fri, 16 May 2014 19:26:52 +0800 Subject: [PATCH 05/39] fix $affected while querying an UPDATE According to http://php.net/mysql_query For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. --- class.MySQL.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index be170ae..1002d5f 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -172,11 +172,10 @@ public function executeSQL($query){ if($this->result = mysql_query($query, $this->databaseLink)){ if (gettype($this->result) === 'resource') { $this->records = @mysql_num_rows($this->result); - $this->affected = @mysql_affected_rows($this->databaseLink); } else { $this->records = 0; - $this->affected = 0; } + $this->affected = @mysql_affected_rows($this->databaseLink); if($this->records > 0){ $this->arrayResults(); @@ -375,4 +374,4 @@ public function closeConnection(){ mysql_close($this->databaseLink); } } -} \ No newline at end of file +} From 57f05076200b04ce9efaea472aefa6a4d7de0e3e Mon Sep 17 00:00:00 2001 From: filippelli Date: Fri, 24 Oct 2014 14:23:27 +0200 Subject: [PATCH 06/39] Update class.MySQL.php Added a destructor, is needed in case of cleaning up permanent connections --- class.MySQL.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/class.MySQL.php b/class.MySQL.php index be170ae..c88c6df 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -53,7 +53,13 @@ function __construct($database, $username, $password, $hostname='localhost', $po $this->Connect(); } + /* ******************* + * Class Destructor * + * *******************/ + function __destruct(){ + $this->closeConnection(); + } /* ******************* * Private Functions * @@ -375,4 +381,4 @@ public function closeConnection(){ mysql_close($this->databaseLink); } } -} \ No newline at end of file +} From 9ae008a8f9aee8fcf5e5d1e439ffcdfa23ac14a6 Mon Sep 17 00:00:00 2001 From: filippelli Date: Tue, 28 Oct 2014 14:26:00 +0100 Subject: [PATCH 07/39] Update class.MySQL.php Set attributes to private Added commit and rollback methods; Added charset management (experimental); Removed useless setting. Forces commit before closing. --- class.MySQL.php | 46 +++++++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index c88c6df..4b3f76f 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -23,20 +23,20 @@ class MySQL { // Base variables - var $lastError; // Holds the last error - var $lastQuery; // Holds the last query - var $result; // Holds the MySQL query result - var $records; // Holds the total number of records returned - var $affected; // Holds the total number of records affected - var $rawResults; // Holds raw 'arrayed' results - var $arrayedResult; // Holds an array of the result + private $lastError; // Holds the last error + private $lastQuery; // Holds the last query + private $result; // Holds the MySQL query result + private $records; // Holds the total number of records returned + private $affected; // Holds the total number of records affected + private $rawResults; // Holds raw 'arrayed' results + private $arrayedResult; // Holds an array of the result - var $hostname; // MySQL Hostname - var $username; // MySQL Username - var $password; // MySQL Password - var $database; // MySQL Database + private $hostname; // MySQL Hostname + private $username; // MySQL Username + private $password; // MySQL Password + private $database; // MySQL Database - var $databaseLink; // Database Connection Link + private $databaseLink; // Database Connection Link @@ -44,13 +44,13 @@ class MySQL { * Class Constructor * * *******************/ - function __construct($database, $username, $password, $hostname='localhost', $port=3306){ + function __construct($database, $username, $password, $hostname='localhost', $port=3306, $persistant = false){ $this->database = $database; $this->username = $username; $this->password = $password; $this->hostname = $hostname.':'.$port; - $this->Connect(); + $this->Connect($persistant); } /* ******************* @@ -85,6 +85,8 @@ private function Connect($persistant = false){ $this->lastError = 'Could not connect to database: ' . mysql_error($this->databaseLink); return false; } + + $this->setCharset(); // TODO: remove forced charset find out a specific management return true; } @@ -124,7 +126,8 @@ private function SecureData($data, $types){ private function CleanData($data, $type = ''){ switch($type) { case 'none': - $data = $data; + // useless do not reaffect just do nothing + //$data = $data; break; case 'str': $data = settype( $data, 'string'); @@ -197,7 +200,18 @@ public function executeSQL($query){ } } + public function commit(){ + return mysql_query("COMMIT", $this->databaseLink); + } + + public function rollback(){ + return mysql_query("ROLLBACK", $this->databaseLink); + } + public function setCharset( $charset = 'UTF8' ) { + return mysql_set_charset ( $this->SecureData($charset,'string'), $this->databaseLink); + } + // Adds a record to the database based on the array key names public function insert($table, $vars, $exclude = '', $datatypes){ @@ -378,6 +392,8 @@ public function countRows($from, $where=''){ // Closes the connections public function closeConnection(){ if($this->databaseLink){ + // Commit before closing just in case :) + $this->commit(); mysql_close($this->databaseLink); } } From dcede6a045131ce66dec56f65ed7ddde21015cdb Mon Sep 17 00:00:00 2001 From: filippelli Date: Tue, 28 Oct 2014 14:29:52 +0100 Subject: [PATCH 08/39] Update class.MySQL.php Assume that some fields needs to be public --- class.MySQL.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 4b3f76f..06a94f7 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -23,13 +23,13 @@ class MySQL { // Base variables - private $lastError; // Holds the last error - private $lastQuery; // Holds the last query - private $result; // Holds the MySQL query result - private $records; // Holds the total number of records returned - private $affected; // Holds the total number of records affected - private $rawResults; // Holds raw 'arrayed' results - private $arrayedResult; // Holds an array of the result + public $lastError; // Holds the last error + public $lastQuery; // Holds the last query + public $result; // Holds the MySQL query result + public $records; // Holds the total number of records returned + public $affected; // Holds the total number of records affected + public $rawResults; // Holds raw 'arrayed' results + public $arrayedResult; // Holds an array of the result private $hostname; // MySQL Hostname private $username; // MySQL Username From fa9f5ce57c4af48663f4d1a593bafc22d9b95bbb Mon Sep 17 00:00:00 2001 From: filippelli Date: Sat, 8 Nov 2014 14:41:06 +0100 Subject: [PATCH 09/39] Correction of mysql_insert_id the command mysql_insert_id was related to the lastest database connection not to the object related one. --- class.MySQL.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 06a94f7..38ec1ef 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -23,7 +23,7 @@ class MySQL { // Base variables - public $lastError; // Holds the last error + public $lastError; // Holds the last error public $lastQuery; // Holds the last query public $result; // Holds the MySQL query result public $records; // Holds the total number of records returned @@ -380,7 +380,7 @@ public function arrayResultsWithKey($key='id'){ // Returns last insert ID public function lastInsertID(){ - return mysql_insert_id(); + return mysql_insert_id($this->databaseLink); } // Return number of rows From a55420802690b20eeedb844b121860023d0cec56 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Thu, 4 Dec 2014 14:21:07 +0000 Subject: [PATCH 10/39] Added PDO class I'm now using instead of class.MySQL.php --- class.PDO.php | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 class.PDO.php diff --git a/class.PDO.php b/class.PDO.php new file mode 100644 index 0000000..b9afdef --- /dev/null +++ b/class.PDO.php @@ -0,0 +1,72 @@ +connect(); + } + + function add_table_prefix($string){ + return DATABASE_PREFIX . $string; + } + + + function prep_query($query){ + return $this->pdo->prepare($query); + } + + + function connect(){ + if(!$this->pdo){ + + $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST; + $user = DATABASE_USER; + $password = DATABASE_PASS; + + try { + $this->pdo = new PDO($dsn, $user, $password); + return true; + } catch (PDOException $e) { + $this->error = $e->getMessage(); + die($this->error); + return false; + } + }else{ + $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); + return true; + } + } + + + function table_exists($table_name){ + $stmt = $this->prep_query('SHOW TABLES LIKE ?'); + $stmt->execute(array($this->add_table_prefix($table_name))); + return $stmt->rowCount() > 0; + } + + + function execute($query, $values = array()){ + $stmt = $this->pdo->prepare($query); + $stmt->execute($values); + return $stmt; + } + + function fetch($query, $values = array()){ + $stmt = $this->execute($query, $values); + return $stmt->fetch(PDO::FETCH_ASSOC); + } + + function fetchAll($query, $values = array()){ + $stmt = $this->execute($query, $values); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + function lastInsertId(){ + return $this->pdo->lastInsertId(); + } + +} \ No newline at end of file From 6201cd541b992ac39a7193cbc24a6ec4f850b834 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Wed, 17 Dec 2014 20:51:55 +0000 Subject: [PATCH 11/39] PDO Class Updates execute, fetch and fetchAll can now accept a single string as the second parameter if only one is needed (seems pointless sending an array with one item) Also, the fetchAll function accepts a third parameter to allow you to return an array with a key being a column from the database as opposed to the standard indexed array. --- class.PDO.php | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/class.PDO.php b/class.PDO.php index b9afdef..a32f0d7 100644 --- a/class.PDO.php +++ b/class.PDO.php @@ -49,20 +49,46 @@ function table_exists($table_name){ } - function execute($query, $values = array()){ + function execute($query, $values = null){ + if($values == null){ + $values = array(); + }else if(!is_array($values)){ + $values = array($values); + } $stmt = $this->pdo->prepare($query); $stmt->execute($values); return $stmt; } - function fetch($query, $values = array()){ + function fetch($query, $values = null){ + if($values == null){ + $values = array(); + }else if(!is_array($values)){ + $values = array($values); + } $stmt = $this->execute($query, $values); return $stmt->fetch(PDO::FETCH_ASSOC); } - function fetchAll($query, $values = array()){ + function fetchAll($query, $values = null, $key = null){ + if($values == null){ + $values = array(); + }else if(!is_array($values)){ + $values = array($values); + } $stmt = $this->execute($query, $values); - return $stmt->fetchAll(PDO::FETCH_ASSOC); + $results = $stmt->fetchAll(PDO::FETCH_ASSOC); + + // Allows the user to retrieve results using a + // column from the results as a key for the array + if($key != null && $results[0][$key]){ + $keyed_results = array(); + foreach($results as $result){ + $keyed_results[$result[$key]] = $result; + } + $results = $keyed_results; + } + return $results; } function lastInsertId(){ From 5444aed4f506b5411fd0d8338fa81913bf0ffadf Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Wed, 17 Dec 2014 21:23:06 +0000 Subject: [PATCH 12/39] Removed add_table_prefix function --- class.PDO.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/class.PDO.php b/class.PDO.php index a32f0d7..8f7ff0a 100644 --- a/class.PDO.php +++ b/class.PDO.php @@ -10,10 +10,6 @@ function __construct() { $this->connect(); } - function add_table_prefix($string){ - return DATABASE_PREFIX . $string; - } - function prep_query($query){ return $this->pdo->prepare($query); From ad5ba18365f8fd5eeb7415d941d274267d34fe87 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Wed, 17 Dec 2014 21:23:37 +0000 Subject: [PATCH 13/39] Updated README's for new PDO version --- class.MySQL.README.md | 126 +++++++++++++++++++++++++++++++++++++ readme.md | 140 ++++++++++++++++++++++-------------------- 2 files changed, 201 insertions(+), 65 deletions(-) create mode 100644 class.MySQL.README.md diff --git a/class.MySQL.README.md b/class.MySQL.README.md new file mode 100644 index 0000000..035145e --- /dev/null +++ b/class.MySQL.README.md @@ -0,0 +1,126 @@ +PHP MySQL Class +=============== + +This is the README for the class.MySQL.php class that I no longer support as the `mysql_*` functions are deprecated. + +This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions. + + +Latest Changes +-------------- + +I have refactored the entire class, and improved the code somewhat. This means that some things now work differently to the original version. + + +Setup +----- + +Simply include this class into your project like so: + +`include_once('/path/to/class.MySQL.php');` + +Then invoke the class in your project using the class constructor (which now sets the db credentials): + +`$oMySQL = new MySQL(MYSQL_NAME, MYSQL_USER, MYSQL_PASS, [MYSQL_HOST]);` + +`MYSQL_NAME` The name of your database + +`MYSQL_USER` Your username for the server / database + +`MYSQL_PASS` Your password for the server / database + +`MYSQL_HOST` The hostname of the MySQL server (*optional*, defaults to 'localhost') + + +Usage +----- + +To use this class, you'd first init the object like so (using example credentials): + +`$oMySQL = new MySQL('my_database','username','password');` + +Provided you see no errors, you are now connected and can execute full MySQL queries using: + +`$oMySQL->ExecuteSQL($query);` + +`ExecuteSQL()` will return an array of results, or a true (if an UPDATE or DELETE). + +There are other functions such as `Insert()`, `Delete()` and `Select()` which may or may not help with your queries to the database. + +Example +------- + +To show you how easy this class is to use, consider you have a table called *admin*, which contains the following: + +``` ++----+--------------+ +| id | username | ++----+--------------+ +| 1 | superuser | +| 2 | a1phanumeric | ++----+--------------+ +``` + +To add a user, you'd simply use: + +``` +$newUser = array('username' => 'Thrackhamator'); +$oMySQL->Insert($newUser, 'admin'); +``` + +And voila: + +``` ++----+---------------+ +| id | username | ++----+---------------+ +| 1 | superuser | +| 2 | a1phanumeric | +| 3 | Thrackhamator | ++----+---------------+ +``` + +To get the results into a usable array, just use `$oMySQL->Select('admin')` ...for example, doing the following: + +`print_r($oMySQL->Select('admin'));` + +will yield: + +``` +Array +( + [0] => Array + ( + [id] => 1 + [username] => superuser + ) + + [1] => Array + ( + [id] => 2 + [username] => a1phanumeric + ) + + [2] => Array + ( + [id] => 3 + [username] => Thrackhamator + ) + +) +``` + +### License + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . \ No newline at end of file diff --git a/readme.md b/readme.md index 45fc325..4ea8ddc 100644 --- a/readme.md +++ b/readme.md @@ -1,113 +1,123 @@ -PHP MySQL Class +Important Notice =============== -This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions. +As of December 2014 I decided to upload the PHP MySQL Class I wrote a while back, and now use on a daily basis. It's PDO based (the `mysql_*` functions were due to be deprecated quite a while back now!). + +The old version is still a part of this repo for now, and the readme is still available [here](class.MySQL.README.md). + -Latest Changes --------------- +PHP MySQL Class +=============== -I have refactored the entire class, and improved the code somewhat. This means that some things now work differently to the original version. +This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions. Setup ----- -Simply include this class into your project like so: +Firstly, define four constants for the host, database name, username and password: + +`define('DATABASE_NAME', 'my_database');` -`include_once('/path/to/class.MySQL.php');` +`define('DATABASE_USER', 'username');` -Then invoke the class in your project using the class constructor (which now sets the db credentials): +`define('DATABASE_PASS', 'password');` -`$oMySQL = new MySQL(MYSQL_NAME, MYSQL_USER, MYSQL_PASS, [MYSQL_HOST]);` +`define('DATABASE_HOST', 'localhost');` -`MYSQL_NAME` The name of your database +Then, simply include this class into your project like so: -`MYSQL_USER` Your username for the server / database +`include_once('/path/to/class.PDO.php');` -`MYSQL_PASS` Your password for the server / database +Then invoke the class: -`MYSQL_HOST` The hostname of the MySQL server (*optional*, defaults to 'localhost') +`$DB = new PDO();` -Usage +Direct Queries ----- -To use this class, you'd first init the object like so (using example credentials): +To perform direct queries where you don't need to return any results (such as update, insert etc...), just do the following: -`$oMySQL = new MySQL('my_database','username','password');` +`$DB->execute("UPDATE customers SET email = 'newemail@domain.com' WHERE username = 'a1phanumeric'");` -Provided you see no errors, you are now connected and can execute full MySQL queries using: +That's the easiest way to use the class, but we should be utilising prepared statements now. This means no more escaping shizzle! To utilise prepared statements, just change the above code to the following: -`$oMySQL->ExecuteSQL($query);` +`$DB->execute("UPDATE customers SET email = ? WHERE username = ?", array('newemail@domain.com', 'a1phanumeric'));` -`ExecuteSQL()` will return an array of results, or a true (if an UPDATE or DELETE). +The class will invoke PDO's prepared statements and put the email and username in their place respectively, as well as escape all values passed to it. **Note:** You don't need to put the speechmarks in on the query, the **?** is enough, and PDO will sort that out for you. -There are other functions such as `Insert()`, `Delete()` and `Select()` which may or may not help with your queries to the database. -Example -------- +Fetching Rows +----- -To show you how easy this class is to use, consider you have a table called *admin*, which contains the following: +To perform select queries with this class, the syntax is similar to the above, but we have two functions we can utilise, `fetch` and `fetchAll`. -``` -+----+--------------+ -| id | username | -+----+--------------+ -| 1 | superuser | -| 2 | a1phanumeric | -+----+--------------+ -``` +`fetch` simply returns one row, useful for getting a user by their ID for example. This returns an associative array and looks like: -To add a user, you'd simply use: +`$user = $DB->fetch("http://github.com/SELECT%20*%20FROM%20users%20WHERE%20id%20=%20?", $id);` -``` -$newUser = array('username' => 'Thrackhamator'); -$oMySQL->Insert($newUser, 'admin'); -``` +Now `$user` will contain an array of the fields for the row where there query matches. Oh, what's that? We didn't pass an array as the second parameter we just passed a single variable? That's cool, the class will treat a single variable the same as if you passed `array($id)`. It's just a handy little time-saver. + +`fetchAll` is used to fetch multiple rows, the parameters are similar, but the result returns an array of records: -And voila: +`$counties = $DB->fetchAll("SELECT * FROM counties");` + +The above will return a list of counties (in the UK) in my database like so: ``` -+----+---------------+ -| id | username | -+----+---------------+ -| 1 | superuser | -| 2 | a1phanumeric | -| 3 | Thrackhamator | -+----+---------------+ +[0] => Array +( + [id] => 1 + [county] => London +) + +[1] => Array +( + [id] => 2 + [county] => Bedfordshire +) + +[2] => Array +( + [id] => 3 + [county] => Buckinghamshire +) ``` -To get the results into a usable array, just use `$oMySQL->Select('admin')` ...for example, doing the following: +However, what if I want to loop over some raw data and check if the data matches the county name? To do that means either looping over these results every time, or shifting the key to the root dimension of the multi-dimensional array. However, if we pass a third variable, we can have that column as the key: + +`$counties = $DB->fetchAll("SELECT * FROM counties", null, 'county');` -`print_r($oMySQL->Select('admin'));` +**Note:** I passed null as the second paramater as we're not passing any variables into the query to be escaped. -will yield: +This will now return an array like the following: ``` -Array +[London] => Array ( - [0] => Array - ( - [id] => 1 - [username] => superuser - ) - - [1] => Array - ( - [id] => 2 - [username] => a1phanumeric - ) - - [2] => Array - ( - [id] => 3 - [username] => Thrackhamator - ) + [id] => 1 + [county] => London +) +[Bedfordshire] => Array +( + [id] => 2 + [county] => Bedfordshire +) + +[Buckinghamshire] => Array +( + [id] => 3 + [county] => Buckinghamshire ) ``` +So of course we could now do something like: + +`if(isset($counties[$raw_data['county_name']])){ //Do something }` + ### License This program is free software: you can redistribute it and/or modify From 6d4a6e6e594539597541dd59d8ea2a3863ba61d1 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Thu, 18 Dec 2014 11:17:25 +0000 Subject: [PATCH 14/39] Updated to use persistent connections. --- class.PDO.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/class.PDO.php b/class.PDO.php index 8f7ff0a..f77ee22 100644 --- a/class.PDO.php +++ b/class.PDO.php @@ -24,7 +24,7 @@ function connect(){ $password = DATABASE_PASS; try { - $this->pdo = new PDO($dsn, $user, $password); + $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); return true; } catch (PDOException $e) { $this->error = $e->getMessage(); From a5e7683b65eab7090703ee14894458d911918415 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Mon, 22 Dec 2014 09:43:00 +0000 Subject: [PATCH 15/39] Oops - wrong class name! Fixed. --- class.PDO.php => class.DBPDO.php | 2 +- readme.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) rename class.PDO.php => class.DBPDO.php (99%) diff --git a/class.PDO.php b/class.DBPDO.php similarity index 99% rename from class.PDO.php rename to class.DBPDO.php index f77ee22..1fd2ea4 100644 --- a/class.PDO.php +++ b/class.DBPDO.php @@ -1,6 +1,6 @@ Date: Mon, 2 Feb 2015 11:47:24 -0500 Subject: [PATCH 16/39] Update class.MySQL.php Change $wheretypes parameter as default empty array When doing CleanData, the default type will return the data directly --- class.MySQL.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 442fc82..03f21de 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -103,7 +103,7 @@ private function UseDB(){ // Performs a 'mysql_real_escape_string' on the entire array/string - private function SecureData($data, $types){ + private function SecureData($data, $types=array()){ if(is_array($data)){ $i = 0; foreach($data as $key=>$val){ @@ -166,7 +166,6 @@ private function CleanData($data, $type = ''){ $data = filter_var($data, FILTER_VALIDATE_EMAIL); break; default: - $data = ''; break; } return $data; @@ -216,7 +215,7 @@ public function setCharset( $charset = 'UTF8' ) { } // Adds a record to the database based on the array key names - public function insert($table, $vars, $exclude = '', $datatypes){ + public function insert($table, $vars, $exclude = '', $datatypes=array()){ // Catch Exclusions if($exclude == ''){ @@ -242,7 +241,7 @@ public function insert($table, $vars, $exclude = '', $datatypes){ } // Deletes a record from the database - public function delete($table, $where='', $limit='', $like=false, $wheretypes){ + public function delete($table, $where='', $limit='', $like=false, $wheretypes=array()){ $query = "DELETE FROM `{$table}` WHERE "; if(is_array($where) && $where != ''){ // Prepare Variables @@ -268,7 +267,7 @@ public function delete($table, $where='', $limit='', $like=false, $wheretypes){ // Gets a single row from $from where $where is true - public function select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*', $wheretypes){ + public function select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*', $wheretypes=array()){ // Catch Exceptions if(trim($from) == ''){ return false; @@ -302,12 +301,14 @@ public function select($from, $where='', $orderBy='', $limit='', $like=false, $o $query .= ' LIMIT ' . $limit; } - return $this->executeSQL($query); + $result = $this->executeSQL($query); + if(is_array($result)) return $result; + return array(); } // Updates a record in the database based on WHERE - public function update($table, $set, $where, $exclude = '', $datatypes, $wheretypes){ + public function update($table, $set, $where, $exclude = '', $datatypes=array(), $wheretypes=array()){ // Catch Exceptions if(trim($table) == '' || !is_array($set) || !is_array($where)){ return false; From 044c7ecf87ce48885163a47c5bf58dadf0ca6391 Mon Sep 17 00:00:00 2001 From: CyrilCharlier Date: Wed, 1 Apr 2015 13:03:50 +0200 Subject: [PATCH 17/39] Update class.DBPDO.php Use of "prep_query" in execute function. --- class.DBPDO.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/class.DBPDO.php b/class.DBPDO.php index 1fd2ea4..368d3b6 100644 --- a/class.DBPDO.php +++ b/class.DBPDO.php @@ -51,7 +51,7 @@ function execute($query, $values = null){ }else if(!is_array($values)){ $values = array($values); } - $stmt = $this->pdo->prepare($query); + $stmt = $this->prep_query($query); $stmt->execute($values); return $stmt; } @@ -91,4 +91,4 @@ function lastInsertId(){ return $this->pdo->lastInsertId(); } -} \ No newline at end of file +} From ab5c7944796863455d8a97bae45dfa8a8b00a54b Mon Sep 17 00:00:00 2001 From: Jon Walker Date: Wed, 24 Jun 2015 16:57:42 -0500 Subject: [PATCH 18/39] removed table prefix call which was missing. --- class.DBPDO.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/class.DBPDO.php b/class.DBPDO.php index 368d3b6..5672757 100644 --- a/class.DBPDO.php +++ b/class.DBPDO.php @@ -40,7 +40,7 @@ function connect(){ function table_exists($table_name){ $stmt = $this->prep_query('SHOW TABLES LIKE ?'); - $stmt->execute(array($this->add_table_prefix($table_name))); + $stmt->execute(array($table_name)); return $stmt->rowCount() > 0; } From cec986a86f92b8a97123b389a8b02e0a1d566d9b Mon Sep 17 00:00:00 2001 From: behzad monfared Date: Thu, 3 Sep 2015 17:41:52 -0700 Subject: [PATCH 19/39] Update class.DBPDO.php add utf8 support --- class.DBPDO.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/class.DBPDO.php b/class.DBPDO.php index 368d3b6..951c4b1 100644 --- a/class.DBPDO.php +++ b/class.DBPDO.php @@ -19,7 +19,7 @@ function prep_query($query){ function connect(){ if(!$this->pdo){ - $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST; + $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST.';charset=utf8'; $user = DATABASE_USER; $password = DATABASE_PASS; From af9fe9ab6d4ba9083586e105963c91a419e37b42 Mon Sep 17 00:00:00 2001 From: kaysen Date: Mon, 7 Nov 2016 15:51:37 +0800 Subject: [PATCH 20/39] FIX: update and delete --- class.MySQL.php | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index effe482..0f977bf 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -261,7 +261,13 @@ public function delete($table, $where='', $limit='', $like=false, $wheretypes=ar $query .= ' LIMIT ' . $limit; } - return $this->executeSQL($query); + $result = $this->executeSQL($query); + + if((int) @mysql_affected_rows($this->databaseLink) == 0){ + return false; + } + + return $result; } @@ -344,7 +350,13 @@ public function update($table, $set, $where, $exclude = '', $datatypes=array(), $query = substr($query, 0, -5); - return $this->executeSQL($query); + $result = $this->executeSQL($query); + + if((int) @mysql_affected_rows($this->databaseLink) == 0){ + return false; + } + + return $result; } // 'Arrays' a single result From 763ae064622c44fe12ae069c7eec4f8ac9822058 Mon Sep 17 00:00:00 2001 From: kaysen Date: Mon, 7 Nov 2016 16:45:21 +0800 Subject: [PATCH 21/39] MOD: class.MySQL.php --- test.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 test.php diff --git a/test.php b/test.php new file mode 100644 index 0000000..a4e4801 --- /dev/null +++ b/test.php @@ -0,0 +1,18 @@ +'kaysen', 'age'=>27, 'created'=>time()); +$status = $DB->insert('kaysen_tab', $insertData); +var_dump($status); + */ + +/* +$status = $DB->update('kaysen_tab', array('age'=>666), array('id'=>1)); +var_dump($status); + */ + +$status = $DB->delete('kaysen_tab', array('id'=>1)); +var_dump($status); From 5ccb5210e6bccfe5f5077438a33fb224c5916424 Mon Sep 17 00:00:00 2001 From: kaysen Date: Mon, 7 Nov 2016 16:49:43 +0800 Subject: [PATCH 22/39] Revert "MOD: class.MySQL.php" This reverts commit 763ae064622c44fe12ae069c7eec4f8ac9822058. --- test.php | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 test.php diff --git a/test.php b/test.php deleted file mode 100644 index a4e4801..0000000 --- a/test.php +++ /dev/null @@ -1,18 +0,0 @@ -'kaysen', 'age'=>27, 'created'=>time()); -$status = $DB->insert('kaysen_tab', $insertData); -var_dump($status); - */ - -/* -$status = $DB->update('kaysen_tab', array('age'=>666), array('id'=>1)); -var_dump($status); - */ - -$status = $DB->delete('kaysen_tab', array('id'=>1)); -var_dump($status); From 2e213511ece132429bae95fa1261dc26087173f5 Mon Sep 17 00:00:00 2001 From: kaysen Date: Mon, 7 Nov 2016 16:50:34 +0800 Subject: [PATCH 23/39] MOD: class.MySQL.php --- class.MySQL.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/class.MySQL.php b/class.MySQL.php index 0f977bf..3429fcd 100644 --- a/class.MySQL.php +++ b/class.MySQL.php @@ -263,7 +263,7 @@ public function delete($table, $where='', $limit='', $like=false, $wheretypes=ar $result = $this->executeSQL($query); - if((int) @mysql_affected_rows($this->databaseLink) == 0){ + if($this->affected == 0){ return false; } @@ -352,7 +352,7 @@ public function update($table, $set, $where, $exclude = '', $datatypes=array(), $result = $this->executeSQL($query); - if((int) @mysql_affected_rows($this->databaseLink) == 0){ + if($this->affected == 0){ return false; } From f8c3f52ccb49e8c2bc3eae3e37c049407f63a133 Mon Sep 17 00:00:00 2001 From: Ed Date: Mon, 17 May 2021 15:37:51 +0100 Subject: [PATCH 24/39] Added composer.json --- .gitignore | 1 + composer.json | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 .gitignore create mode 100644 composer.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57872d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor/ diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b3dd7ab --- /dev/null +++ b/composer.json @@ -0,0 +1,14 @@ +{ + "name": "a1phanumeric/php-mysql-class", + "description": "This is a simple to use PHP MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions.", + "type": "library", + "license": "GPL", + "authors": [ + { + "name": "Ed", + "email": "ed@rockfire.co" + } + ], + "minimum-stability": "dev", + "require": {} +} From ab69133546f3f8a301c5a32aac7320267483fd60 Mon Sep 17 00:00:00 2001 From: Ed Date: Mon, 17 May 2021 15:40:28 +0100 Subject: [PATCH 25/39] Updated composer --- composer.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/composer.json b/composer.json index b3dd7ab..857cadf 100644 --- a/composer.json +++ b/composer.json @@ -2,13 +2,11 @@ "name": "a1phanumeric/php-mysql-class", "description": "This is a simple to use PHP MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions.", "type": "library", - "license": "GPL", "authors": [ { "name": "Ed", "email": "ed@rockfire.co" } ], - "minimum-stability": "dev", "require": {} } From c6ad610ef2e8c376b77f516a6043cbbf69e6ae82 Mon Sep 17 00:00:00 2001 From: Ed Date: Mon, 17 May 2021 15:44:57 +0100 Subject: [PATCH 26/39] Updated composer license --- composer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/composer.json b/composer.json index 857cadf..181ce2c 100644 --- a/composer.json +++ b/composer.json @@ -2,6 +2,7 @@ "name": "a1phanumeric/php-mysql-class", "description": "This is a simple to use PHP MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions.", "type": "library", + "license": "MIT", "authors": [ { "name": "Ed", From 5909df0be896824982477e5be15c2715981bf5ef Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Mar 2023 11:27:51 +0000 Subject: [PATCH 27/39] Update composer.json --- composer.json | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 181ce2c..0d55f9d 100644 --- a/composer.json +++ b/composer.json @@ -9,5 +9,8 @@ "email": "ed@rockfire.co" } ], - "require": {} + "require": {}, + "autoload": { + "psr-4": { "A1phanumeric\\": "A1phanumeric" } + } } From 73ee8d774d37fa59696a6833f099445cbe592f09 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Mar 2023 11:28:11 +0000 Subject: [PATCH 28/39] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0d55f9d..e224ec1 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,7 @@ "authors": [ { "name": "Ed", - "email": "ed@rockfire.co" + "email": "ed.rackham19@gmail.com" } ], "require": {}, From f6d2ae7916c0357b78d7eb212e4686c035fcc9ae Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Mar 2023 11:28:38 +0000 Subject: [PATCH 29/39] Update class.DBPDO.php --- class.DBPDO.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/class.DBPDO.php b/class.DBPDO.php index a1322d5..35d179c 100644 --- a/class.DBPDO.php +++ b/class.DBPDO.php @@ -1,5 +1,7 @@ Date: Fri, 10 Mar 2023 14:39:52 +0000 Subject: [PATCH 30/39] Updated autoload --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index e224ec1..e0a7cca 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": {}, - "autoload": { - "psr-4": { "A1phanumeric\\": "A1phanumeric" } + "autoload": { + "psr-4": { "A1phanumeric\\": "" } } } From d5e8c3eceda7fb011df7b78365ccb67a06f9cf7a Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Fri, 10 Mar 2023 14:46:13 +0000 Subject: [PATCH 31/39] Renamed main class file for composer autoloading --- class.DBPDO.php => DBPDO.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename class.DBPDO.php => DBPDO.php (100%) diff --git a/class.DBPDO.php b/DBPDO.php similarity index 100% rename from class.DBPDO.php rename to DBPDO.php From 8930083466d1954da855fd99035131e0b60e11a8 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Fri, 10 Mar 2023 15:19:40 +0000 Subject: [PATCH 32/39] Release for composer v2.0 --- DBPDO.php | 19 +++++++++++++++---- readme.md | 14 +++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/DBPDO.php b/DBPDO.php index 35d179c..990be3e 100644 --- a/DBPDO.php +++ b/DBPDO.php @@ -2,13 +2,24 @@ namespace A1phanumeric; +use \PDO; +use \PDOException; + class DBPDO { public $pdo; private $error; + private $dbname; + private $dbhost; + private $dbuser; + private $dbpass; - function __construct() { + function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass= '') { + $this->dbhost = $dbhost; + $this->dbname = $dbname; + $this->dbuser = $dbuser; + $this->dbpass = $dbpass; $this->connect(); } @@ -21,9 +32,9 @@ function prep_query($query){ function connect(){ if(!$this->pdo){ - $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST.';charset=utf8'; - $user = DATABASE_USER; - $password = DATABASE_PASS; + $dsn = 'mysql:dbname=' . $this->dbname . ';host=' . $this->dbhost . ';charset=utf8'; + $user = $this->dbuser; + $password = $this->dbpass; try { $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); diff --git a/readme.md b/readme.md index b61ad31..8bd7fb2 100644 --- a/readme.md +++ b/readme.md @@ -12,8 +12,20 @@ PHP MySQL Class This is a simple to use MySQL class that easily bolts on to any existing PHP application, streamlining your MySQL interactions. +Setup v2.0+ +----- + +Include the class using composer as below: + +`composer require a1phanumeric/php-mysql-class` + +To use in your project, use the following: + +`use A1phanumeric\DBPDO;` + +`$DB = new DBPDO('db_name', 'db_host', 'db_user', 'db_pass');` -Setup +###Setup Before v2.0 ----- Firstly, define four constants for the host, database name, username and password: From 1a43e20054d3fdbf5c436e7df285120b9794ef61 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Fri, 10 Mar 2023 15:21:48 +0000 Subject: [PATCH 33/39] Update readme.md --- readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 8bd7fb2..9dfcf7f 100644 --- a/readme.md +++ b/readme.md @@ -25,7 +25,7 @@ To use in your project, use the following: `$DB = new DBPDO('db_name', 'db_host', 'db_user', 'db_pass');` -###Setup Before v2.0 +### Setup Before v2.0 ----- Firstly, define four constants for the host, database name, username and password: @@ -143,4 +143,4 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License -along with this program. If not, see . \ No newline at end of file +along with this program. If not, see . From 5e6459cb873a6347e37e6fe04c299cc68a8396b0 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Thu, 23 Mar 2023 10:35:10 +0000 Subject: [PATCH 34/39] Update readme.md --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 9dfcf7f..c7720b4 100644 --- a/readme.md +++ b/readme.md @@ -23,7 +23,7 @@ To use in your project, use the following: `use A1phanumeric\DBPDO;` -`$DB = new DBPDO('db_name', 'db_host', 'db_user', 'db_pass');` +`$DB = new DBPDO('db_host', 'db_name', 'db_user', 'db_pass');` ### Setup Before v2.0 ----- From 9c189d039a68211828100bcd592fc09cb057df86 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Wed, 29 Nov 2023 11:01:21 +0000 Subject: [PATCH 35/39] Fixed bug with getting keyed results --- DBPDO.php | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/DBPDO.php b/DBPDO.php index 990be3e..dccd848 100644 --- a/DBPDO.php +++ b/DBPDO.php @@ -90,12 +90,14 @@ function fetchAll($query, $values = null, $key = null){ // Allows the user to retrieve results using a // column from the results as a key for the array - if($key != null && $results[0][$key]){ - $keyed_results = array(); - foreach($results as $result){ - $keyed_results[$result[$key]] = $result; + if(!empty($results)){ + if ($key != null && $results[0][$key]) { + $keyed_results = array(); + foreach ($results as $result) { + $keyed_results[$result[$key]] = $result; + } + $results = $keyed_results; } - $results = $keyed_results; } return $results; } From 7f8c3e3b7a7e115f0da3cb4304b0f23592280664 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Jan 2025 09:30:55 +0000 Subject: [PATCH 36/39] Update DBPDO.php Updated DBPDO to use a a singleton instance if needed throughout the app --- DBPDO.php | 90 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 25 deletions(-) diff --git a/DBPDO.php b/DBPDO.php index dccd848..507e206 100644 --- a/DBPDO.php +++ b/DBPDO.php @@ -5,84 +5,124 @@ use \PDO; use \PDOException; -class DBPDO { +class DBPDO +{ + private static $instance = null; public $pdo; private $error; private $dbname; private $dbhost; private $dbuser; private $dbpass; + private $orderwise; + public static function getInstance($dbhost, $dbname, $dbuser, $dbpass, $orderwise = false) + { + if (self::$instance === null) { + self::$instance = new self($dbhost, $dbname, $dbuser, $dbpass, $orderwise); + } + return self::$instance; + } - function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass= '') { + function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass = '', $orderwise = false) + { $this->dbhost = $dbhost; $this->dbname = $dbname; $this->dbuser = $dbuser; $this->dbpass = $dbpass; + $this->orderwise = $orderwise; $this->connect(); } + // Disallow cloning and unserializing + private function __clone() {} + private function __wakeup() {} + - function prep_query($query){ + function prep_query($query) + { return $this->pdo->prepare($query); } - function connect(){ - if(!$this->pdo){ - - $dsn = 'mysql:dbname=' . $this->dbname . ';host=' . $this->dbhost . ';charset=utf8'; + function connect() + { + if (!$this->pdo) { + if($this->orderwise){ + $dsn = 'sqlsrv:Server=' . $this->dbhost . ';Database=' . $this->dbname . ';Encrypt=no'; + }else{ + $dsn = 'mysql:dbname=' . $this->dbname . ';host=' . $this->dbhost . ';charset=utf8mb4'; + } $user = $this->dbuser; $password = $this->dbpass; try { - $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); + if($this->orderwise){ + $this->pdo = new PDO($dsn, $user, $password); + }else{ + $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); + } return true; } catch (PDOException $e) { $this->error = $e->getMessage(); - die($this->error); + // die($this->error); return false; } - }else{ - $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); + } else { + $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); return true; } } - function table_exists($table_name){ + function table_exists($table_name) + { $stmt = $this->prep_query('SHOW TABLES LIKE ?'); $stmt->execute(array($table_name)); return $stmt->rowCount() > 0; } - function execute($query, $values = null){ - if($values == null){ + function execute($query, $values = null, $debug = false) + { + if ($values == null) { $values = array(); - }else if(!is_array($values)){ + } else if (!is_array($values)) { $values = array($values); } $stmt = $this->prep_query($query); - $stmt->execute($values); + if($debug){ + echo $query; + print_r($values); + die(); + } + try { + $stmt->execute($values); + } catch (PDOException $e) { + $this->error = $e->getMessage(); + die($query . "
\n" . $this->error); + return false; + } return $stmt; } - function fetch($query, $values = null){ - if($values == null){ + function fetch($query, $values = null) + { + if ($values == null) { $values = array(); - }else if(!is_array($values)){ + } else if (!is_array($values)) { $values = array($values); } $stmt = $this->execute($query, $values); return $stmt->fetch(PDO::FETCH_ASSOC); } - function fetchAll($query, $values = null, $key = null){ - if($values == null){ + function fetchAll($query, $values = null, $key = null) + { + if ($values == null) { $values = array(); - }else if(!is_array($values)){ + } else if (!is_array($values)) { $values = array($values); } $stmt = $this->execute($query, $values); @@ -91,7 +131,7 @@ function fetchAll($query, $values = null, $key = null){ // Allows the user to retrieve results using a // column from the results as a key for the array if(!empty($results)){ - if ($key != null && $results[0][$key]) { + if ($key != null) { $keyed_results = array(); foreach ($results as $result) { $keyed_results[$result[$key]] = $result; @@ -102,8 +142,8 @@ function fetchAll($query, $values = null, $key = null){ return $results; } - function lastInsertId(){ + function lastInsertId() + { return $this->pdo->lastInsertId(); } - } From 7356e616abaa4c11300a9f4f2c1ec464931dddc4 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Jan 2025 09:34:23 +0000 Subject: [PATCH 37/39] Update readme.md --- readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/readme.md b/readme.md index c7720b4..e0b457f 100644 --- a/readme.md +++ b/readme.md @@ -25,6 +25,10 @@ To use in your project, use the following: `$DB = new DBPDO('db_host', 'db_name', 'db_user', 'db_pass');` +Or, if wanting to use as a singleton instance: + +`$DB = DBPDO::getInstance('db_host', 'db_name', 'db_user', 'db_pass');` + ### Setup Before v2.0 ----- From d94dea03c79d902f29d2ca08fdef13bfc8d8e07b Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Tue, 7 Jan 2025 09:38:09 +0000 Subject: [PATCH 38/39] Update DBPDO.php Removed debug 'dies' --- DBPDO.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/DBPDO.php b/DBPDO.php index 507e206..fdb357a 100644 --- a/DBPDO.php +++ b/DBPDO.php @@ -36,8 +36,8 @@ function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass = '', $or } // Disallow cloning and unserializing - private function __clone() {} - private function __wakeup() {} + private function __clone() {} + private function __wakeup() {} function prep_query($query) @@ -66,7 +66,6 @@ function connect() return true; } catch (PDOException $e) { $this->error = $e->getMessage(); - // die($this->error); return false; } } else { @@ -101,7 +100,6 @@ function execute($query, $values = null, $debug = false) $stmt->execute($values); } catch (PDOException $e) { $this->error = $e->getMessage(); - die($query . "
\n" . $this->error); return false; } return $stmt; From e74de62049938b80f896082a39de6fabb0eb17d6 Mon Sep 17 00:00:00 2001 From: Ed Rackham Date: Fri, 17 Jan 2025 11:30:26 +0000 Subject: [PATCH 39/39] Removed OW referenced for SQLServer references --- DBPDO.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/DBPDO.php b/DBPDO.php index fdb357a..5356d2b 100644 --- a/DBPDO.php +++ b/DBPDO.php @@ -15,23 +15,23 @@ class DBPDO private $dbhost; private $dbuser; private $dbpass; - private $orderwise; + private $sqlserver; - public static function getInstance($dbhost, $dbname, $dbuser, $dbpass, $orderwise = false) + public static function getInstance($dbhost, $dbname, $dbuser, $dbpass, $sqlserver = false) { if (self::$instance === null) { - self::$instance = new self($dbhost, $dbname, $dbuser, $dbpass, $orderwise); + self::$instance = new self($dbhost, $dbname, $dbuser, $dbpass, $sqlserver); } return self::$instance; } - function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass = '', $orderwise = false) + function __construct($dbhost = '', $dbname = '', $dbuser = '', $dbpass = '', $sqlserver = false) { $this->dbhost = $dbhost; $this->dbname = $dbname; $this->dbuser = $dbuser; $this->dbpass = $dbpass; - $this->orderwise = $orderwise; + $this->sqlserver = $sqlserver; $this->connect(); } @@ -49,7 +49,7 @@ function prep_query($query) function connect() { if (!$this->pdo) { - if($this->orderwise){ + if($this->sqlserver){ $dsn = 'sqlsrv:Server=' . $this->dbhost . ';Database=' . $this->dbname . ';Encrypt=no'; }else{ $dsn = 'mysql:dbname=' . $this->dbname . ';host=' . $this->dbhost . ';charset=utf8mb4'; @@ -58,7 +58,7 @@ function connect() $password = $this->dbpass; try { - if($this->orderwise){ + if($this->sqlserver){ $this->pdo = new PDO($dsn, $user, $password); }else{ $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));