0
0
This repository has been archived on 2020-11-15. You can view files and clone it, but cannot push or open issues or pull requests.
OpenShorte.old/lib/php/classes/Database.php

61 lines
2.3 KiB
PHP
Raw Permalink Normal View History

<?php
class Database {
private $config;
private $connection;
private $statement;
public function __construct ( $config ) {
if ( isset ( $config ) && isset ( $config [ 'host' ] ) && isset ( $config [ 'username' ] ) && isset ( $config [ 'password' ] ) && isset ( $config [ 'name' ] ) && isset ( $config [ 'port' ] ) ) {
$this->config = $config;
}
else {
die ( "You can't initialize a database connection without proper configuration." );
}
}
public function connect ( ) : void {
try {
$this->connection = new PDO ( "mysql:dbname=" . $this->config [ 'name' ] . ";host=" . $this->config [ 'host' ] . ":" . $this->config [ 'port' ], $this->config [ 'username' ], $this->config [ 'password' ] );
}
catch ( PDOException $exception ) {
die ( "Database connection failed: " . $exception->getMessage ( ) );
}
}
public function query ( string $query ) {
$result = $this->connection->query ( $query );
if ( $result === false ) {
die ( "Query execution error: " . $this->connection->errorInfo ( ) [ 2 ] );
}
return $result;
}
public function prepare ( string $query ) : void {
if ( ! ( $this->statement = $this->connection->prepare ( $query ) ) ) {
die ( "Prepare failed: " . $this->statement->errorInfo ( ) [ 2 ] );
}
}
public function bind ( array $params ) : void {
foreach ( $params as $paramKey => $paramValue ) {
if ( ! $this->statement->bindValue ( $paramKey, $paramValue ) ) {
die ( "Binding parameters failed: " . $this->statement->errorInfo ( ) [ 2 ] );
}
}
}
public function execute ( ) : void {
if ( $this->statement->execute ( ) === false ) {
die ( "Execute failed: " . $this->statement->errorInfo ( ) [ 2 ] );
}
}
public function debugDumpParams ( ) : void {
$this->statement->debugDumpParams ( );
}
public function get_result ( ) : PDOStatement {
return $this->statement;
}
}