| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- <?php
- class db
- {
- private static PDO $dbh;
- private static string $error = '';
- private static PDOStatement $stmt;
- private static function connect(): void
- {
- if (isset(self::$dbh)) {
- return;
- }
- $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
- $options = [
- PDO::ATTR_PERSISTENT => true,
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
- ];
- try {
- self::$dbh = new PDO($dsn, DB_USER, DB_PASS, $options);
- } catch (PDOException $e) {
- self::$error = $e->getMessage();
- throw new Exception("Database connection error: " . self::$error);
- }
- }
- public static function version(): string
- {
- self::connect();
- return self::$dbh->getAttribute(PDO::ATTR_SERVER_VERSION);
- }
- public static function query(string $query): void
- {
- self::connect();
- self::$stmt = self::$dbh->prepare($query);
- }
- public static function bind(string $param, mixed $value = null, ?int $type = null): void
- {
- if (is_null($type)) {
- $type = match (true) {
- is_int($value) => PDO::PARAM_INT,
- is_bool($value) => PDO::PARAM_BOOL,
- is_null($value) => PDO::PARAM_NULL,
- default => PDO::PARAM_STR,
- };
- }
- self::$stmt->bindValue($param, $value, $type);
- }
- public static function execute(): bool
- {
- self::connect();
- if (class_exists('debug') && method_exists('debug', 'isFile') && debug::isFile("sql")) {
- ob_start();
- $result = self::$stmt->execute();
- self::$stmt->debugDumpParams();
- $debugOutput = ob_get_clean();
- debug::logSession($debugOutput);
- return $result;
- }
- return self::$stmt->execute();
- }
- public static function resultset(): array
- {
- self::execute();
- return self::$stmt->fetchAll(PDO::FETCH_ASSOC);
- }
- public static function single(): array|false
- {
- self::execute();
- return self::$stmt->fetch(PDO::FETCH_ASSOC);
- }
- public static function rowCount(): int
- {
- return self::$stmt->rowCount();
- }
- public static function lastInsertId(): string
- {
- self::connect();
- return self::$dbh->lastInsertId();
- }
- public static function beginTransaction(): bool
- {
- self::connect();
- return self::$dbh->beginTransaction();
- }
- public static function endTransaction(): bool
- {
- self::connect();
- return self::$dbh->commit();
- }
- public static function cancelTransaction(): bool
- {
- self::connect();
- return self::$dbh->rollBack();
- }
- public static function debugDumpParams(): void
- {
- self::connect();
- self::$stmt->debugDumpParams();
- }
- public static function queryError(): void
- {
- self::connect();
- $qError = self::$dbh->errorInfo();
- if (!empty($qError[2])) {
- echo "Query Error: " . $qError[2];
- }
- }
- public static function getError(): string
- {
- return self::$error;
- }
- }
|