-
Notifications
You must be signed in to change notification settings - Fork 0
/
crud.php
103 lines (77 loc) · 2.28 KB
/
crud.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
<?php
class CRUD
{
private $db;
public function __construct($db)
{
$this->db = $db;
}
public function create($table, $data)
{
$fields = implode(", ", array_keys($data));
$values = ":" . implode(", :", array_keys($data));
$query = "INSERT INTO $table ($fields) VALUES ($values)";
$stmt = $this->db->prepare($query);
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
return $stmt->execute();
}
public function read($table, $id = null)
{
if ($id) {
$query = "SELECT * FROM $table WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindValue(':id', $id);
$stmt->execute();
return $stmt->fetch();
} else {
$query = "SELECT * FROM $table";
$stmt = $this->db->prepare($query);
$stmt->execute();
return $stmt->fetchAll();
}
}
public function update($table, $data, $id)
{
$fields = implode(" = :", array_keys($data)) . " = :";
$query = "UPDATE $table SET $fields WHERE id = :id";
$stmt = $this->db->prepare($query);
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
$stmt->bindValue(':id', $id);
return $stmt->execute();
}
public function delete($table, $id)
{
$query = "DELETE FROM $table WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindValue(':id', $id);
return $stmt->execute();
}
}
// CREATE
$pdo = new PDO("mysql:host=localhost;dbname=your_db", "username", "password");
$crud = new CRUD($pdo);
// To create a new record, you can call the `create` method and pass in the table name and an associative array of data:
$data = array(
"name" => "John Doe",
"email" => "[email protected]",
"phone" => "555-555-5555"
);
$crud->create("users", $data);
// READ
// To read a single record
$user = $crud->read("users", 1);
// To read all records
$users = $crud->read("users");
// UPDATE
$data = array(
"name" => "Jane Doe",
"email" => "[email protected]",
"phone" => "555-555-5555"
);
$crud->update("users", $data, 1);
// DELETE
$crud->delete("users", 1);