Last active
September 15, 2024 15:32
-
-
Save jason-napolitano/acc6219c93b816d80ba26fe5932bff0e to your computer and use it in GitHub Desktop.
A simple, yet effective PDO wrapper class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A simple, yet effective PDO wrapper class | |
* | |
* @author Jason Napolitano | |
* @license MIT | |
* | |
* @see https://www.php.net/manual/en/class.pdostatement.php | |
* @see https://www.php.net/manual/en/class.pdo.php | |
*/ | |
final class Database | |
{ | |
/** @var PDO $connection PDO connection */ | |
private PDO $connection; | |
/** @var PDOStatement|null $statement Prepared PDO statement */ | |
private ?PDOStatement $statement = null; | |
/** @var array $options PDO options */ | |
private array $options = [ | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION | |
]; | |
/** | |
* Builds a new database object | |
* | |
* @param string $username Username | |
* @param string $password Password | |
* @param string $hostname Hostname | |
* @param string $database Database | |
*/ | |
public function __construct( | |
private readonly string $username, | |
private readonly string $password, | |
private readonly string $hostname, | |
private readonly string $database, | |
) { | |
$this->connection = new PDO("mysql:host=$this->hostname;dbname=$this->database;", $this->username, $this->password, $this->options); | |
} | |
/** | |
* Generate a prepared query | |
* | |
* @param string $query | |
* @param array $params | |
* | |
* @return void | |
*/ | |
public function query(string $query, array $params = []): void | |
{ | |
$this->statement = $this->connection->prepare(trim($query)); | |
$this->statement->execute($params); | |
} | |
/** | |
* Get the results of a query | |
* | |
* @return array | |
*/ | |
public function get(): array | |
{ | |
return $this->statement->fetchAll(PDO::FETCH_ASSOC); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: