68 lines
No EOL
2 KiB
PHP
68 lines
No EOL
2 KiB
PHP
<?php
|
|
class Database {
|
|
private $dbh;
|
|
private $stmt;
|
|
private $error;
|
|
|
|
public function __construct() {
|
|
$host = Config::get('DB_HOST', 'localhost');
|
|
$user = Config::get('DB_USER', 'root');
|
|
$pass = Config::get('DB_PASS', '');
|
|
$dbname = Config::get('DB_NAME', '');
|
|
|
|
// Wenn gar keine DB konfiguriert ist, direkt Exception werfen
|
|
if (empty($dbname)) {
|
|
throw new Exception("Keine Datenbank in .env konfiguriert.");
|
|
}
|
|
|
|
$dsn = 'mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8mb4';
|
|
|
|
$options = [
|
|
PDO::ATTR_PERSISTENT => true,
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
|
|
];
|
|
|
|
try {
|
|
$this->dbh = new PDO($dsn, $user, $pass, $options);
|
|
} catch (PDOException $e) {
|
|
$this->error = $e->getMessage();
|
|
// Exception werfen statt sterben!
|
|
throw new Exception("Datenbank-Verbindungsfehler.");
|
|
}
|
|
}
|
|
|
|
public function query($sql) {
|
|
$this->stmt = $this->dbh->prepare($sql);
|
|
}
|
|
|
|
public function bind($param, $value, $type = null) {
|
|
if (is_null($type)) {
|
|
switch (true) {
|
|
case is_int($value): $type = PDO::PARAM_INT; break;
|
|
case is_bool($value): $type = PDO::PARAM_BOOL; break;
|
|
case is_null($value): $type = PDO::PARAM_NULL; break;
|
|
default: $type = PDO::PARAM_STR;
|
|
}
|
|
}
|
|
$this->stmt->bindValue($param, $value, $type);
|
|
}
|
|
|
|
public function execute() {
|
|
return $this->stmt->execute();
|
|
}
|
|
|
|
public function resultSet() {
|
|
$this->execute();
|
|
return $this->stmt->fetchAll();
|
|
}
|
|
|
|
public function single() {
|
|
$this->execute();
|
|
return $this->stmt->fetch();
|
|
}
|
|
|
|
public function rowCount() {
|
|
return $this->stmt->rowCount();
|
|
}
|
|
} |