This repository has been archived by the owner on Mar 19, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CRUD.php
125 lines (114 loc) · 2.73 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
class CRUD {
private $conn;
private $table;
protected function __construct($host = "localhost", $user = "root", $pass = "", $db = "", $port = 3306) {
$mysqli = new mysqli($host, $user, $pass, $db, $port);
$this->conn = $mysqli;
}
public function setTable($table) {
$this->table = $table;
return $this;
}
public function create($data = array(), $debug = false) {
if(empty($this->table)) { return false; }
$count = count($data);
if($count > 0) {
$columns = "";
$values = "";
$i = 0;
foreach($data as $k => $v) {
$columns .= $k;
$values .= '"'.self::filter($v).'"';
if($i < ($count - 1)) {
$columns .= ", ";
$values .= ", ";
}
$i++;
}
$query = sprintf("INSERT INTO %s (%s) VALUES (%s)", $this->table, $columns, $values);
if($debug) {
return $query;
} else {
return $this->conn->query($query);
}
} else {
return false;
}
}
public function read($columns = array(), $where = "", $debug = false) {
if(empty($this->table)) { return false; }
$count = count($columns);
if($count > 0) {
$col = "";
$i = 0;
foreach($columns as $v) {
$col .= $v;
if($i < ($count - 1)) {
$col .= ", ";
}
$i++;
}
} else {
$col = "*";
}
$query = sprintf("SELECT %s FROM %s", $col, $this->table);
$query .= ( empty($where) ? "" : " WHERE ".$where );
if($debug) {
return $query;
} else {
return $this->conn->query($query);
}
}
public function update($data = array(), $where = "", $debug = false) {
if(empty($this->table)) { return false; }
$count = count($data);
if($count > 0) {
$a = "";
$i = 0;
foreach($data as $k => $v) {
$a .= $k.' = "'.self::filter($v).'"';
if($i < ($count - 1)) {
$a .= ", ";
}
$i++;
}
$query = sprintf("UPDATE %s SET %s", $this->table, $a);
$query .= ( empty($where) ? "" : " WHERE ".$where );
if($debug) {
return $query;
} else {
return $this->conn->query($query);
}
} else {
return false;
}
}
public function delete($where = "", $debug = false) {
if(empty($this->table)) { return false; }
if(empty($where)) {
return false;
}
$query = sprintf("DELETE FROM %s WHERE %s", $this->table, $where);
if($debug) {
return $query;
} else {
return $this->conn->query($query);
}
}
private static function filter($str) {
return ( get_magic_quotes_gpc() ? $str : addslashes($str) );
}
public static function bind($str, $data) {
$count = count($data);
if($count > 0) {
foreach($data as $k => $v) {
$str = str_ireplace($k, self::filter($v), $str);
}
return $str;
} else {
return "";
}
}
}
?>