generated from teknasyon-bootcamp/homework4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.class.php
102 lines (74 loc) · 2.56 KB
/
db.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
<?php
class DB{
protected string $user = "root";
protected string $pass = "";
protected string $db_name = "post";
protected string $host_name ="localhost";
public function __construct()
{
}
public function createConn() : PDO{
try{
return new PDO("mysql:host=$this->host_name;dbname=$this->db_name","$this->user","$this->pass");
}catch(PDOException $e){
echo $e-> getMessage();
}
}
public function get(string $table_name, int $id) : array{
$conn = $this->createConn();
$stmt = $conn->prepare("SELECT * FROM $table_name WHERE id = $id");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function getAll(string $table_name) : array{
$conn = $this->createConn();
$stmt = $conn->prepare("SELECT * FROM $table_name");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function create(string $table_name, array $columns): void{
$conn = $this->createConn();
$sql = "INSERT INTO $table_name (";
foreach($columns as $column){
foreach ($column as $key => $col){
$sql .= $key. ", ";
}
}
$sql = rtrim($sql, " , ");
$sql .= ") ";
$sql .= "VALUES (";
foreach($columns as $column) {
foreach ($column as $col){
$sql .= "'". $col . "'". ",";
}
}
$sql = rtrim($sql," , ");
$sql .= ")";
$stmt = $conn->prepare($sql);
$stmt-> execute();
}
public function update(string $table_name, int $id, array $columns){
$conn = $this->createConn();
$sql = "UPDATE $table_name SET ";
foreach($columns as $column){
foreach ($column as $key => $col){
if(is_string($col)){
$sql .= $key . " = " . "'" . $col . "'" . ", ";
}else{
$sql .= $key . " = " . $col . ", ";
}
}
}
$sql = rtrim($sql, " , ");
$sql .= " WHERE id = $id";
$stmt = $conn-> prepare($sql);
$stmt->execute();
echo $stmt->rowCount() . " kayıt başarılı bir şekilde değiştirildi.";
}
public function delete(string $table_name, int $id){
$conn = $this->createConn();
$sql = "DELETE FROM $table_name WHERE id = $id";
$stmt = $conn->prepare($sql);
$stmt-> execute();
}
}