Advertisement
JBHUTT09

Database

Aug 23rd, 2017
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.07 KB | None | 0 0
  1. <?php
  2.     namespace MyNameSpace;
  3.    
  4.     use \PDO;
  5.     use MyNameSpace\Helpers\ArrayHelper;
  6.     /**
  7.      * Database class
  8.      *
  9.      * @package MyPackage
  10.      * @subpackage Database
  11.      * @author JBHUTT09
  12.      */
  13.     class Database {
  14.         const RETURN_QUERY = 0;
  15.         const RETURN_ROW_COUNT = 1;
  16.         const RETURN_LAST_INSERTED = 2;
  17.         const RETURN_ALL_ROWS = 3;
  18.        
  19.        
  20.         protected $available_connections = [];
  21.         protected $connections = [];
  22.        
  23.         public function __construct( array $db_connections ) {
  24.             $this->available_connections = $db_connections;
  25.             return $this;
  26.         }
  27.        
  28.         /**
  29.          * Checks $connections for the specified index. If the index is not found, attempts to create a PDO instance using the provided settings and store it in $connections.
  30.          *
  31.          * @param string $connection_type The index of the desired connection config array passed to the constructor.
  32.          * @param bool $return (optional) If true, return the PDO object. If false, return bool true. Defaults to false.
  33.          * @return bool|PDO Returns bool false on failure. Success return type determined by $return param.
  34.          */
  35.         private function openLink( string $connection_type, $return=false ) {
  36.             if ( !isset( $this->connections[ $connection_type ] ) ) {
  37.                 if ( !isset( $this->available_connections[ $connection_type ] ) || !ArrayHelper::multiIsset( $this->available_connections[ $connection_type ], [ 'host', 'database', 'charset', 'user', 'pass' ] ) ) return false;
  38.                 try {
  39.                     $this->connections[ $connection_type ] = new PDO(
  40.                         'mysql:host='.$this->available_connections[ $connection_type ][ 'host' ].';dbname='.$this->available_connections[ $connection_type ][ 'database' ].';charset='.$this->available_connections[ $connection_type ][ 'charset' ],
  41.                         ''.$this->available_connections[ $connection_type ][ 'user' ].'',
  42.                         ''.$this->available_connections[ $connection_type ][ 'pass' ].''
  43.                     );
  44.                 }
  45.                 catch ( Exception $e ) {
  46.                     return false;
  47.                 }
  48.             }
  49.             return $return ? $this->connections[ $connection_type ] : true;
  50.         }
  51.        
  52.         private function executeQuery( string $connection_type, string $query_text, array $prepared = [], $return=self::RETURN_QUERY ) {
  53.             if ( $this->openLink( $connection_type ) === false ) return false;
  54.             $query = $this->connections[ $connection_type ]->prepare( $query_text );
  55.             if ( $query->execute( $prepared ) !== false ) {
  56.                 if ( $return === self::RETURN_QUERY ) return $query;
  57.                 elseif ( $return === self::RETURN_ROW_COUNT ) return $query->rowCount();
  58.                 elseif ( $return === self::RETURN_ALL_ROWS ) return $query->fetchAll( PDO::FETCH_ASSOC );
  59.                 elseif ( $return === self::RETURN_LAST_INSERTED ) return $this->connections[ $connection_type ]->lastInsertId();
  60.             }
  61.             //$this->logQuery( $query, $query_text, $prepared );
  62.             return false;
  63.         }
  64.        
  65.         /*
  66.          * Perform a SELECT query
  67.          *
  68.          * @param string $connection_type The connection type
  69.          * @param string $table The table to select from
  70.          * @param array $args (optional) An array of options in the following format:
  71.          *      select: (string|array)
  72.          *          A column name |
  73.          *          an array of column names (supports associative arrays for 'column (key) AS alias (value)' selections) |
  74.          *          an array of assoc arrays with the keys 'value' (column name) and 'function' (MySQL function ie DECOMPRESS)
  75.          *      where: (string) a MySQL WHERE clause (do not include 'WHERE'). May contain PDO tokens.
  76.          *      prepared: (assoc array) A valid array of PDO tokens and values. Required if where contains PDO tokens
  77.          *      order: (string|array)
  78.          */
  79.         public function select( string $connection_type, string $table, array $args = [] ) {
  80.             // build select statement
  81.             if ( !isset( $args[ 'select' ] ) ) $selection = '*';
  82.             elseif ( is_array( $args[ 'select' ] ) ) {
  83.                 $selection = '';
  84.                 $n = 0;
  85.                 // iterate through columns to select.
  86.                 // if $key is not numeric, we assume $key is the column and $value is the desired alias: SELECT $key AS $value
  87.                 // otherwise we assume $value is the column and ignore $key
  88.                 foreach ( $args[ "select" ] AS $key => $value ) {
  89.                     if ( $n > 0 )  $selection .= ',';
  90.                     // if $value is an associative array, we assume we are to apply a function to the column.
  91.                     if ( ArrayHelper::isAssoc( $value ) ) $selection .= ( ( !is_numeric( $key ) ) ? $value[ 'function' ]."( $key ) AS ".$value[ 'value' ] : $value[ 'function' ].'( '.$value[ 'value' ].' )' );
  92.                     else $selection .= "`$table`.`".( ( !is_numeric( $key ) ) ? "$key` AS `$value" : $value ).'`';
  93.                     $n++;
  94.                 }
  95.             }
  96.             else $selection = '`'.$args[ 'select' ].'`';
  97.            
  98.             if ( isset( $args[ 'where' ] ) ) {
  99.                 $where = 'WHERE '.$args[ 'where' ];
  100.                 $prepared = isset( $args[ 'prepared' ] ) ? $args[ 'prepared' ] : [];
  101.             }
  102.             else {
  103.                 $where = '';
  104.                 $prepared = [];
  105.             }
  106.            
  107.             if ( isset( $args[ 'order' ] ) ) {
  108.                 if ( is_array( $args[ 'order' ] ) ) {
  109.                     $order = 'ORDER BY ';
  110.                     $n = 0;
  111.                     $is_assoc = ArrayHelper::isAssoc( $args[ 'order' ] );
  112.                     foreach ( $args[ 'order' ] AS $key => $value ) {
  113.                         if ( $n > 0 ) $order .= ',';
  114.                         $order .= ( ( $is_assoc ) ? "$key $value" : $value );
  115.                         $n++;
  116.                     }
  117.                 }
  118.                 else if ( is_string( $args[ 'order' ] ) && strpos( strtolower( ltrim( $args[ 'order' ] ) ), 'order by' ) !== 0 ) $order = 'ORDER BY '.$args[ 'order' ];
  119.                 else $order = $args[ 'order' ];
  120.             }
  121.             else $order = '';
  122.            
  123.             if ( isset( $args[ 'limit' ] ) ) {
  124.                 if ( is_array( $args[ 'limit' ] ) && count( $args[ 'limit' ] ) == 2 ) $limit = 'LIMIT '.implode( ',', $args[ 'limit' ] );
  125.                 else if ( is_int( $args[ 'limit' ] ) || ( is_string( $args[ 'limit' ] ) && strpos( strtolower( ltrim( $args[ 'limit' ] ) ), 'limit' ) !== 0 ) ) $limit = 'LIMIT '.$args[ 'limit' ];
  126.                 else $limit = $args[ 'limit' ];
  127.             }
  128.             else $limit = '';
  129.            
  130.             return $this->executeQuery( $connection_type, "SELECT $selection FROM $table $where $order $limit;", $prepared, self::RETURN_ALL_ROWS );
  131.         }
  132.        
  133.         /**
  134.          * Insert new database row
  135.          *
  136.          * @param string $connection_type The database connection to use.
  137.          * @param string $table The database table to insert into.
  138.          * @param array $prepared Associative array of the columns => values to insert.
  139.          * @return int|bool The inserted row id on success. Bool false on failure.
  140.          */
  141.         public function insert( string $connection_type, string $table, array $prepared ) {
  142.             $columns = '';
  143.             $values = '';
  144.             //put column names and values into strings formatted for query
  145.             foreach( $prepared as $name => $value ) {
  146.                 $columns .= ",`$name`";
  147.                 if ( is_array( $value ) ) {
  148.                     $values .= ','.$value[ 'function' ]."( :$name )";
  149.                     $prepared[ $name ] = $value[ 'value' ];
  150.                 }
  151.                 else $values .= ",:$name";
  152.             }
  153.             $values = trim( $values, ',' ); //remove the extra commas from the front of the strings
  154.             $columns = trim( $columns, ',' );
  155.             return $this->executeQuery( $connection_type, "INSERT INTO `$table` ($columns) VALUES ($values);", $prepared, self::RETURN_LAST_INSERTED );
  156.         }
  157.        
  158.         /**
  159.          * Execute UPDATE query.
  160.          *
  161.          * @param string $connection_type The database connection to use.
  162.          * @param string $table The table to update.
  163.          * @param array $to_update Associative array of columns to update mapped to their new values.
  164.          * @param string $where (optional) The WHERE condition. Not supplying a WHERE condition will apply the update to every row! Be careful!
  165.          * @param array $prepared (optional) A valid PDO prepared array. Required when using a WHERE condition containing PDO tokens.
  166.          *
  167.          */
  168.         public function update( string $connection_type, string $table, array $to_update, string $where=NULL, array $prepared=[] ) {
  169.             $where = isset( $where ) ? "WHERE $where" : '';
  170.             $set = '';
  171.             foreach ( $to_update as $key => $value ) {
  172.                 if ( isset( $prepared[ $key ] ) ) return false;
  173.                 $set .= "`$key`=:$key,";
  174.             }
  175.             $set = rtrim( $set, ',' );
  176.             return $this->executeQuery( $connection_type, "UPDATE `$table` SET $set $where;", array_merge( $to_update, $prepared ), self::RETURN_ROW_COUNT );
  177.         }
  178.        
  179.         /**
  180.          * Execute DELETE query.
  181.          *
  182.          * @param string $connection_type The database connection to use.
  183.          * @param string $table The table to delete from.
  184.          * @param string $where (optional) The WHERE condition. Not supplying a WHERE condition will apply the delete every row! Be careful!
  185.          * @param array $prepared (optional) A valid PDO prepared array. Required when using a WHERE condition containing PDO tokens.
  186.          *
  187.          */
  188.         public function delete( string $connection_type, string $table, string $where=NULL, array $prepared=[] ) {
  189.             $where = isset( $where ) ? "WHERE $where" : '';
  190.             return $this->executeQuery( $connection_type, "DELETE FROM `$table` $where;", $prepared, self::RETURN_ROW_COUNT );
  191.         }
  192.        
  193.         /**
  194.          * Run a custom MySQL query
  195.          *
  196.          * @param string $connection_type The database connection to use.
  197.          * @param string $query_text The MySQL query to run.
  198.          * @param array $prepared (optional) A valid PDO prepared array. Required if $query_text contains PDO tokens.
  199.          * @param $return (optional) The format in which to return the query results. Defaults to Database::RETURN_QUERY which returns the PDO query object.
  200.          * @return mixed The query results in the specified format.
  201.          */
  202.         public function custom( string $connection_type, string $query_text, array $prepared=[], $return=self::RETURN_QUERY ) {
  203.             return $this->executeQuery( $connection_type, $query_text, $prepared, $return );
  204.         }
  205.     }
  206. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement