Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Database {
- const RETURN_QUERY = 0;
- const RETURN_ROW_COUNT = 1;
- const RETURN_LAST_INSERTED = 2;
- const RETURN_ALL_ROWS = 3;
- protected $available_connections = [];
- public $connections = [];
- public function __construct( array $db_connections ) {
- $this->available_connections = $db_connections;
- return $this;
- }
- /**
- * 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.
- *
- * @param string $connection_type The index of the desired connection config array passed to the constructor.
- * @param bool $return (optional) If true, return the PDO object. If false, return bool true. Defaults to false.
- * @return bool|PDO Returns bool false on failure. Success return type determined by $return param.
- */
- private function openLink( string $connection_type, $return=false ) {
- if ( !isset( $this->connections[ $connection_type ] ) ) {
- if ( !isset( $this->available_connections[ $connection_type ] ) || !ArrayHelper::multiIsset( $this->available_connections[ $connection_type ], [ 'host', 'database', 'charset', 'user', 'pass' ] ) ) return false;
- try {
- $this->connections[ $connection_type ] = new PDO(
- 'mysql:host='.$this->available_connections[ $connection_type ][ 'host' ].';dbname='.$this->available_connections[ $connection_type ][ 'database' ].';charset='.$this->available_connections[ $connection_type ][ 'charset' ],
- ''.$this->available_connections[ $connection_type ][ 'user' ].'',
- ''.$this->available_connections[ $connection_type ][ 'pass' ].''
- );
- }
- catch ( Exception $e ) {
- return false;
- }
- }
- return $return ? $this->connections[ $connection_type ] : true;
- }
- public function closeLink( $connection_type ) {
- if ( isset( $this->connections[ $connection_type ] ) ) {
- $this->connections[ $connection_type ] = NULL;
- }
- }
- public function query( string $connection_type, string $query_text, array $prepared = [], $return=self::RETURN_QUERY ) {
- if ( $this->openLink( $connection_type ) === false ) return false;
- $query = $this->connections[ $connection_type ]->prepare( $query_text );
- if ( $query->execute( $prepared ) !== false ) {
- if ( $return === self::RETURN_QUERY ) return $query;
- elseif ( $return === self::RETURN_ROW_COUNT ) return $query->rowCount();
- elseif ( $return === self::RETURN_ALL_ROWS ) return $query->fetchAll( PDO::FETCH_ASSOC );
- elseif ( $return === self::RETURN_LAST_INSERTED ) return $this->connections[ $connection_type ]->lastInsertId();
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement