63689ae0e9
Converted MySQLi Database.php class to PHP_PDO objects
61 lines
2.3 KiB
PHP
61 lines
2.3 KiB
PHP
<?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;
|
|
}
|
|
}
|