-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
45 lines (39 loc) · 1.03 KB
/
Copy pathdb.php
File metadata and controls
45 lines (39 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
function get_config(): array
{
static $config = null;
if ($config === null) {
$config = require __DIR__ . '/../config.php';
}
return $config;
}
function db(): PDO
{
static $pdo = null;
if ($pdo !== null) {
return $pdo;
}
$cfg = get_config();
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s;charset=utf8mb4',
$cfg['db_host'],
$cfg['db_port'],
$cfg['db_name']
);
try {
$pdo = new PDO($dsn, $cfg['db_user'], $cfg['db_pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
http_response_code(500);
header('Content-Type: application/json');
echo json_encode([
'message' => 'Database connection failed. Run setup.php first and verify config.php.',
'error' => $e->getMessage(),
]);
exit;
}
return $pdo;
}