1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace HexMakina\Crudites\Grammar\Query; |
4
|
|
|
|
5
|
|
|
class Insert extends Query |
6
|
|
|
{ |
7
|
|
|
private array $binding_names; |
8
|
|
|
|
9
|
|
|
public function __construct(string $table, array $dat_ass) |
10
|
|
|
{ |
11
|
|
|
// Check if the given data is a non-empty array, and throw an exception if it is not |
12
|
|
|
if (empty($dat_ass)) { |
13
|
|
|
throw new \InvalidArgumentException('EMPTY_DATA'); |
14
|
|
|
} |
15
|
|
|
$this->table = $table; |
16
|
|
|
$this->binding_names = []; |
17
|
|
|
// $this->binding_names = $this->addBindings($dat_ass); |
18
|
|
|
|
19
|
|
|
$this->values($dat_ass); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function values(array $dat_ass): self |
23
|
|
|
{ |
24
|
|
|
$this->binding_names []= $this->addBindings($dat_ass); |
25
|
|
|
|
26
|
|
|
return $this; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Generates the SQL INSERT statement |
31
|
|
|
* |
32
|
|
|
* @return string - The generated SQL INSERT statement |
33
|
|
|
*/ |
34
|
|
|
public function statement(): string |
35
|
|
|
{ |
36
|
|
|
// Generate the INSERT statement with backticks around the field names |
37
|
|
|
|
38
|
|
|
$fields_labels = array_shift($this->binding_names); |
39
|
|
|
$fields = array_keys($fields_labels); |
40
|
|
|
$fields = '`' . implode('`,`', $fields) . '`'; |
41
|
|
|
|
42
|
|
|
$bindings = implode(',:', $fields_labels); |
43
|
|
|
|
44
|
|
|
$statement = sprintf('INSERT INTO `%s` (%s) VALUES (:%s)', $this->table, $fields, $bindings); |
45
|
|
|
foreach($this->binding_names as $bindings){ |
46
|
|
|
$statement .= sprintf(',(:%s)', implode(',:', $bindings)); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return $statement; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|