Untitled
unknown
php
3 years ago
2.4 kB
12
Indexable
<?php
namespace App;
class Database
{
private \PDO $db;
private $dsn = null;
private $db_user = null;
private $db_name = null;
private $db_pass = null;
private $db_host = null;
private $query = null;
public function __construct()
{
$this->db_user = get_config('db_user') ?? "root";
$this->db_name = get_config('db_name') ?? "";
$this->db_pass = get_config('db_pass') ?? "";
$this->db_host = get_config('db_host') ?? "localhost";
$this->dsn = "mysql:host=" . $this->db_host . ";dbname=" . $this->db_name;
$this->db = new \PDO($this->dsn, $this->db_user, $this->db_pass);
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING);
}
public function query(string $query)
{
$this->query = $this->db->prepare($query);
}
public function bind(int|string $param, mixed $value, int $type = null)
{
$value = htmlspecialchars(strip_tags($value), ENT_QUOTES, 'UTF-8');
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->query->bindParam($param, $value, $type);
}
public function execute(array $data = null): bool
{
return $this->query->execute($data);
}
public function executeFile(string $sql): int|false
{
return $this->db->exec($sql);
}
public function fetchAll()
{
$this->execute();
return $this->query->fetchAll(PDO::FETCH_OBJ);
}
public function fetchOne(): mixed
{
$this->execute();
return $this->query->fetch(PDO::FETCH_OBJ);
}
public function rowCount(): int
{
return $this->query->rowCount();
}
public function lastInsertId(): string|false
{
return $this->db->lastInsertId();
}
public function get_status(): mixed
{
return $this->db->getAttribute(\PDO::ATTR_CONNECTION_STATUS);
}
public function __destruct()
{
$this->query = null;
}
}
Editor is loading...