Repository navigation
Expand file tree
/
Copy pathDatabase.php
More file actions
66 lines (54 loc) 路 1.5 KB
/
Copy pathDatabase.php
File metadata and controls
66 lines (54 loc) 路 1.5 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
declare(strict_types=1);
namespace App\Config;
use App\Utils\Logger;
use PDO;
use PDOException;
class Database
{
private string $dbHost;
private string $dbUser;
private string $dbPass;
private string $dbName;
private string $dbPort;
private ?PDO $conn = null;
public function __construct()
{
$this->dbHost = $_ENV['DB_HOST'] ?? 'localhost';
$this->dbUser = $_ENV['DB_USER'] ?? 'root';
$this->dbPass = $_ENV['DB_PASS'] ?? '';
$this->dbName = $_ENV['DB_NAME'] ?? '';
$this->dbPort = $_ENV['DB_PORT'] ?? '3306';
}
public function getHost(): string
{
return $this->dbHost;
}
public function getUser(): string
{
return $this->dbUser;
}
public function getDbName(): string
{
return $this->dbName;
}
public function getPort(): string
{
return $this->dbPort;
}
public function connect(): ?PDO
{
$this->conn = null;
try {
$dsn = "mysql:host={$this->dbHost};port={$this->dbPort};dbname={$this->dbName};charset=utf8mb4";
$this->conn = new PDO($dsn, $this->dbUser, $this->dbPass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
Logger::error("Connection failed: " . $e->getMessage());
}
return $this->conn;
}
}