-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.php
More file actions
58 lines (35 loc) · 1.22 KB
/
Copy pathDatabase.php
File metadata and controls
58 lines (35 loc) · 1.22 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
<?php
class Database {
private $db;
public function __construct($config) {
$dsn = $this->getDsn($config);
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
if ($config['driver'] == 'mysql') {
$this->db = new PDO($dsn, $config['user'], $config['password'], $options);
} else {
$this->db = new PDO($dsn, null, null, $options);
}
}
private function getDsn($config) {
$driver = $config['driver'];
if ($driver == 'sqlite') {
return 'sqlite:' . $config['database'];
}
if ($driver == 'mysql') {
return "mysql:host={$config['host']};dbname={$config['dbname']};charset={$config['charset']}";
}
return $driver . ':' . http_build_query($config, '', ';');
}
public function query($query, $class = null, $params = []) {
$prepare = $this->db->prepare($query);
if ($class) {
$prepare->setFetchMode(PDO::FETCH_CLASS, $class);
}
$prepare->execute($params);
return $prepare;
}
}
$database = new Database(config('database'));