-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabase.php
76 lines (64 loc) · 1.89 KB
/
Database.php
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
67
68
69
70
71
72
73
74
75
76
<?php
class Database
{
private PDO $connection;
private PDOStatement $statement;
private bool $success = false;
public function __construct(array $config, string $username = "root", string $password = "")
{
$host = $config['host'];
$port = $config['port'];
$dbname = $config['dbname'];
$charset = $config['charset'];
$username = $config['user'] ?? $username;
$password = $config['password'] ?? $password;
$dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=$charset";
$options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_PERSISTENT => true,
];
$this->connection = new PDO($dsn, $username, $password, $options);
}
public function query(string $query, array|null $params = null): self
{
$this->statement = $this->connection->prepare($query);
$this->success = $this->statement->execute($params);
return $this;
}
public function is_success(): bool
{
return $this->success;
}
public function result(): mixed
{
return $this->statement->fetch();
}
public function result_or_fail(callable $on_fail): mixed
{
$res = $this->statement->fetch();
if (!$res) {
$on_fail();
}
return $res;
}
public function all_results(callable $callback = null): false|array
{
if ($callback) {
return $this->statement->fetchAll(PDO::FETCH_FUNC, $callback);
}
return $this->statement->fetchAll();
}
public function last_insert_id(): false|string
{
return $this->connection->lastInsertId();
}
public function error(): array
{
return $this->statement->errorInfo();
}
}
function connect_db(): Database
{
$config = require 'config.php';
return new Database($config['database']);
}