-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.php
104 lines (82 loc) · 2.23 KB
/
table.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
<?php
// TODO:
// - decide on selection method
// - drop() method
namespace Database;
require_once __DIR__ . '/database.php';
class Table {
protected $database;
protected $table;
function __construct(Database $database, $table){
$this->database = $database;
$this->table = $table;
}
//----------------------------------------
// inserting
//----------------------------------------
function insert(array $values){
$query =
"INSERT INTO `$this->table`" .
' SET ' . $this->prepare_values($values) .
';';
$result = $this->database->execute($query);
return $result;
}
//----------------------------------------
// replaceing
//----------------------------------------
function replace(array $values){
$query =
"REPLACE INTO `$this->table`" .
' SET ' . $this->prepare_values($values) .
';';
$result = $this->database->execute($query);
return $result;
}
//----------------------------------------
// dropping
//----------------------------------------
// "if exists" should be part of the drop() method:
// 1) \Database\Table::IF_EXISTS
// 2) Database\IF_EXISTS
// 3) $table->drop()->execute();
// $table->drop()->if_exists()->execute();
function drop(){
$query = "DROP TABLE `$this->table`;";
$result = $this->database->execute($query);
return $result;
}
function drop_if_exists(){
$query = "DROP TABLE IF EXISTS `$this->table`;";
$result = $this->database->execute($query);
return $result;
}
//----------------------------------------
// preparing values for query
//----------------------------------------
protected function prepare_values(array $values){
$pairs = [];
foreach($values as $key => $value){
$pairs[] = "`$key` = " . $this->prepare_value($value);
}
return implode(', ', $pairs);
}
//----------------------------------------
// preparing value for query
//----------------------------------------
// how should the method behave in case
// of untranslatable types like object?
// map to null? ignore?
protected function prepare_value($value){
switch(gettype($value)){
case 'integer':
case 'double':
return $value;
break;
case 'string':
return "'$value'";
default:
return 'NULL';
}
}
}