-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseTable.php
More file actions
84 lines (61 loc) · 1.9 KB
/
Copy pathDatabaseTable.php
File metadata and controls
84 lines (61 loc) · 1.9 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
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
<?php
namespace CSY2028;
class DatabaseTable {
private $pdo;
private $table;
private $primaryKey;
public function __construct($pdo, $table, $primaryKey = 'id') {
$this->pdo = $pdo;
$this->table = $table;
$this->primaryKey = $primaryKey;
}
public function insert($record) {
$keys = array_keys($record);
$values = implode(', ', $keys);
$valuesWithColon = implode(', :', $keys);
$query = 'INSERT INTO ' . $this->table . ' (' . $values . ') VALUES (:' . $valuesWithColon . ')';
$stmt = $this->pdo->prepare($query);
return $stmt->execute($record);
}
public function update($record) {
$query = 'UPDATE ' . $table . ' SET ';
$parameters = [];
foreach ($record as $key => $value) {
$parameters[] = $key . ' = :' .$key;
}
$query .= implode(', ', $parameters);
$query .= ' WHERE ' . $this->primaryKey . ' = :primaryKey';
$record['primaryKey'] = $record[$this->primaryKey];
$stmt = $this->pdo->prepare($query);
$stmt->execute($record);
}
public function save($record) {
$success = $this->insert($record);
if (!$success) {
$this->update($record);
}
}
public function delete($id) {
$stmt = $this->pdo->prepare('DELETE FROM ' . $this->table . ' WHERE ' . $this->primaryKey . ' = :value');
$criteria = [
'value' => $id
];
$stmt->execute($criteria);
}
public function findById($id) {
$stmt = $this->pdo->prepare('SELECT * FROM ' . $this->table . ' WHERE ' . $this->primaryKey . ' = :value');
$criteria = [
'value' => $id
];
$stmt->execute($criteria);
return $stmt->fetch();
}
public function find($field, $value) {
$stmt = $this->pdo->prepare('SELECT * FROM ' . $this->table . ' WHERE ' . $field . ' = :value');
$criteria = [
'value' => $value
];
$stmt->execute($criteria);
return $stmt->fetchAll();
}
}