-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySqlBuilder.class.php
113 lines (93 loc) · 2.82 KB
/
MySqlBuilder.class.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
namespace App\Core;
class MySqlBuilder implements QueryBuilder
{
private $query;
public function select($table, $columns) : QueryBuilder
{
$this->reset();
$this->query->base = "SELECT " . implode(', ', $columns) . " FROM " . $table;
return $this;
}
/**
* @param $table
* @return QueryBuilder
*/
public function delete($table) : QueryBuilder
{
$this->reset();
$this->query->base = "DELETE FROM " . $table;
return $this;
}
public function reset()
{
$this->query = new \stdClass();
}
/*
public function where($column, $value , $operator = '=') : QueryBuilder
{
$this->query->where[] = " " . $column . " " . $operator . " '" . $value . "'";
return $this;
}
*/
public function where($column, $value, $operator = "="): QueryBuilder
{
$this->query->where[] = " " . $column . " " . $operator . " " . $value ;
return $this;
}
public function limit($from, $offset) : QueryBuilder{
$this->query->limit = " LIMIT " . $from . ", " . $offset;
return $this;
}
public function getQuery(): string
{
$query = $this->query;
$sql = $query->base;
if (!empty($query->join)) {
$sql .= implode(' ', $query->join);
}
if (!empty($query->where)) {
$sql .= " WHERE " . implode(' AND ', $query->where);
}
if (isset($query->limit)) {
$sql .= $query->limit;
}
$sql .= ";";
return $sql;
}
public function rightJoin(string $table, string $fk, string $pk): QueryBuilder
{
$this->query->join[] = " RIGHT JOIN " . $table . " ON " . $pk . " = " . $fk;
return $this;
}
public function leftJoin(string $table, string $fk, string $pk): QueryBuilder
{
$this->query->join[] = " LEFT JOIN " . $table . " ON " . $pk . " = " . $fk;
return $this;
}
/*
public function insert($table, $columns = ' ', $values) : QueryBuilder
{
$this->reset();
$this->query->base = "INSERT INTO " . $table;
if (!empty($columns)) {
$this->query->base .= " (" . implode(', ', $columns) . ")";
}
$this->query->base .= " VALUES (" . implode(', ', $values) . ")";
return $this;
}*/
public function insert(string $table, array $columns): QueryBuilder
{
$this->reset();
$this->query->base = "INSERT INTO " . $table . " (" . implode(", ", $columns) . ") VALUES (";
for ($i = 0; $i < count($columns) ; $i++) {
if($i == 0) {
$this->query->base .= '?';
} else {
$this->query->base .= ', ?';
}
}
$this->query->base .= ')';
return $this;
}
}