50 lines
1.4 KiB
PHP
50 lines
1.4 KiB
PHP
<?php
|
|
/**
|
|
* Database Singleton — PDO Connection
|
|
*/
|
|
|
|
require_once __DIR__ . '/../config.php';
|
|
|
|
class Database
|
|
{
|
|
private static ?PDO $instance = null;
|
|
|
|
private function __construct()
|
|
{
|
|
try {
|
|
$dsn = sprintf(
|
|
'mysql:host=%s;dbname=%s;charset=utf8mb4',
|
|
DB_HOST,
|
|
DB_NAME
|
|
);
|
|
|
|
self::$instance = new PDO($dsn, DB_USER, DB_PASS, [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone = '+03:00'",
|
|
]);
|
|
} catch (PDOException $e) {
|
|
error_log('Database connection failed: ' . $e->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'database_error', 'details' => $e->getMessage(), 'db_host' => DB_HOST, 'db_user' => DB_USER]);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
public static function getInstance(): PDO
|
|
{
|
|
if (self::$instance === null) {
|
|
new self();
|
|
}
|
|
return self::$instance;
|
|
}
|
|
|
|
/** Prevent cloning */
|
|
private function __clone() {}
|
|
public function __wakeup()
|
|
{
|
|
throw new \Exception("Cannot unserialize singleton");
|
|
}
|
|
}
|