1: <?php
2:
3: namespace ngatngay\database;
4:
5: use PDO;
6:
7: class database
8: {
9: private PDO $pdo;
10:
11: public function __construct($pdo = null)
12: {
13: $this->pdo = $pdo;
14: $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_CLASS);
15: $this->pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, [statement::class]);
16: }
17:
18: public function query(string $sql, ?array $params = null)
19: {
20: $stmt = $this->pdo->prepare($sql);
21: $stmt->execute($params);
22:
23: return $stmt;
24: }
25:
26: public function insert(string $table, array $params)
27: {
28: $sql = 'insert into "' . $table . '"'
29: . ' (' . implode(',', $this->buildName(array_keys($params))) . ')'
30: . ' values (' . implode(',', array_fill(0, count($params), '?')) . ')';
31:
32: $this->query($sql, array_values($params));
33:
34: return $this->pdo->lastInsertId();
35: }
36:
37: public function update(string $sql, $params = null)
38: {
39: $stmt = $this->query($sql, $params);
40:
41: return $stmt->rowCount();
42: }
43:
44: public function fetch(string $sql, $params = null)
45: {
46: return $this->query($sql, $params)
47: ->fetch();
48: }
49:
50: public function fetchAll(string $sql, $params = null)
51: {
52: return $this->query($sql, $params)
53: ->fetchAll();
54: }
55:
56: public function fetchColumn(string $sql, $params = null, $column = 0)
57: {
58: $stmt = $this->query($sql, $params);
59: return $stmt->fetchColumn($column);
60: }
61:
62: public function getOffset(int $page, int $perPage)
63: {
64: return $page * $perPage - $perPage;
65: }
66:
67: public function quote(string $str)
68: {
69: return $this->pdo->quote($str);
70: }
71:
72: public function buildName($arr)
73: {
74: return array_map(function ($item) {
75: return '"' . $item . '"';
76: }, $arr);
77: }
78: }
79: