diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57872d0 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/vendor/ diff --git a/DBPDO.php b/DBPDO.php new file mode 100644 index 0000000..5356d2b --- /dev/null +++ b/DBPDO.php @@ -0,0 +1,147 @@ +dbhost = $dbhost; + $this->dbname = $dbname; + $this->dbuser = $dbuser; + $this->dbpass = $dbpass; + $this->sqlserver = $sqlserver; + $this->connect(); + } + + // Disallow cloning and unserializing + private function __clone() {} + private function __wakeup() {} + + + function prep_query($query) + { + return $this->pdo->prepare($query); + } + + + function connect() + { + if (!$this->pdo) { + if($this->sqlserver){ + $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 { + if($this->sqlserver){ + $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(); + 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($table_name)); + return $stmt->rowCount() > 0; + } + + + function execute($query, $values = null, $debug = false) + { + if ($values == null) { + $values = array(); + } else if (!is_array($values)) { + $values = array($values); + } + $stmt = $this->prep_query($query); + if($debug){ + echo $query; + print_r($values); + die(); + } + try { + $stmt->execute($values); + } catch (PDOException $e) { + $this->error = $e->getMessage(); + return false; + } + return $stmt; + } + + 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 = null, $key = null) + { + if ($values == null) { + $values = array(); + } else if (!is_array($values)) { + $values = array($values); + } + $stmt = $this->execute($query, $values); + $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(!empty($results)){ + if ($key != null) { + $keyed_results = array(); + foreach ($results as $result) { + $keyed_results[$result[$key]] = $result; + } + $results = $keyed_results; + } + } + return $results; + } + + function lastInsertId() + { + return $this->pdo->lastInsertId(); + } +} 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/class.MySQL.php b/class.MySQL.php index 13d86f6..3429fcd 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 + 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 - 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,16 +44,22 @@ class MySQL { * Class Constructor * * *******************/ - function __construct($database, $username, $password, $hostname='localhost'){ + function __construct($database, $username, $password, $hostname='localhost', $port=3306, $persistant = false){ $this->database = $database; $this->username = $username; $this->password = $password; - $this->hostname = $hostname; + $this->hostname = $hostname.':'.$port; - $this->Connect(); + $this->Connect($persistant); } + /* ******************* + * Class Destructor * + * *******************/ + function __destruct(){ + $this->closeConnection(); + } /* ******************* * Private Functions * @@ -79,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; } @@ -95,234 +103,313 @@ private function UseDB(){ // Performs a 'mysql_real_escape_string' on the entire array/string - private function SecureData($data){ + private function SecureData($data, $types=array()){ 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; - } + + // 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': + // useless do not reaffect just do nothing + //$data = $data; + break; + case 'str': + case 'string': + settype( $data, 'string'); + break; + case 'int': + case 'integer': + settype( $data, 'integer'); + break; + case 'float': + settype( $data, 'float'); + break; + case 'bool': + case 'boolean': + 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': + settype( $data, 'integer'); + $data = date('Y-m-d H:i:s', $data); + break; + + // 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: + break; + } + return $data; + } + + + + /* ****************** + * Public Functions * + * ******************/ + + // Executes MySQL query + public function executeSQL($query){ + $this->lastQuery = $query; + if($this->result = mysql_query($query, $this->databaseLink)){ + if (gettype($this->result) === 'resource') { + $this->records = @mysql_num_rows($this->result); + } else { + $this->records = 0; + } + $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; + } + } + + public function commit(){ + return mysql_query("COMMIT", $this->databaseLink); } - - - // 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); + + public function rollback(){ + return mysql_query("ROLLBACK", $this->databaseLink); } - - // 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); + + public function setCharset( $charset = 'UTF8' ) { + return mysql_set_charset ( $this->SecureData($charset,'string'), $this->databaseLink); } - - // 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) == ''){ + // Adds a record to the database based on the array key names + public function insert($table, $vars, $exclude = '', $datatypes=array()){ + + // 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=array()){ + $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; + } + + $result = $this->executeSQL($query); + + if($this->affected == 0){ 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)); + return $result; + } - }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)){ + + // Gets a single row from $from where $where is true + public function select($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*', $wheretypes=array()){ + // 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; + } + + $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=array(), $wheretypes=array()){ + // 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); + + $result = $this->executeSQL($query); + + if($this->affected == 0){ 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; - } - // '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; - } + return $result; + } - // Returns last insert ID - function LastInsertID(){ - return mysql_insert_id(); - } + // 'Arrays' a single result + public function arrayResult(){ + $this->arrayedResult = mysql_fetch_assoc($this->result) or die (mysql_error($this->databaseLink)); + return $this->arrayedResult; + } - // Return number of rows - function CountRows($from, $where=''){ - $result = $this->Select($from, $where, '', '', false, 'AND','count(*)'); - return $result["count(*)"]; - } + // 'Arrays' multiple result + public function arrayResults(){ - // Closes the connections - function CloseConnection(){ - if($this->databaseLink){ - mysql_close($this->databaseLink); - } - } -} + 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($this->databaseLink); + } + + // 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){ + // Commit before closing just in case :) + $this->commit(); + mysql_close($this->databaseLink); + } + } +} diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..e0a7cca --- /dev/null +++ b/composer.json @@ -0,0 +1,16 @@ +{ + "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", + "email": "ed.rackham19@gmail.com" + } + ], + "require": {}, + "autoload": { + "psr-4": { "A1phanumeric\\": "" } + } +} diff --git a/readme.md b/readme.md index 45fc325..e0b457f 100644 --- a/readme.md +++ b/readme.md @@ -1,113 +1,139 @@ +Important Notice +=============== + +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). + + + 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` -Latest Changes --------------- +To use in your project, use the following: -I have refactored the entire class, and improved the code somewhat. This means that some things now work differently to the original version. +`use A1phanumeric\DBPDO;` +`$DB = new DBPDO('db_host', 'db_name', 'db_user', 'db_pass');` -Setup +Or, if wanting to use as a singleton instance: + +`$DB = DBPDO::getInstance('db_host', 'db_name', 'db_user', 'db_pass');` + +### Setup Before v2.0 ----- -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.DBPDO.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 DBPDO();` -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: -`print_r($oMySQL->Select('admin'));` +`$counties = $DB->fetchAll("SELECT * FROM counties", null, 'county');` -will yield: +**Note:** I passed null as the second paramater as we're not passing any variables into the query to be escaped. + +This will now return an array like the following: ``` -Array +[London] => Array +( + [id] => 1 + [county] => London +) + +[Bedfordshire] => Array ( - [0] => Array - ( - [id] => 1 - [username] => superuser - ) - - [1] => Array - ( - [id] => 2 - [username] => a1phanumeric - ) - - [2] => Array - ( - [id] => 3 - [username] => Thrackhamator - ) + [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 @@ -121,4 +147,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 .