/
db.php
102 lines (83 loc) · 2.25 KB
/
db.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
<?
class Db {
private $connection;
private static $db;
public static function getInstance($option = null){
if (self::$db == null){
self::$db = new Db($option);
}
return self::$db;
}
public function __construct($option = null){
if ($option != null){
$host = $option['host'];
$user = $option['user'];
$pass = $option['pass'];
$name = $option['name'];
} else {
global $config;
$host = $config['db']['host'];
$user = $config['db']['user'];
$pass = $config['db']['pass'];
$name = $config['db']['name'];
}
$this->connection = new mysqli($host, $user, $pass, $name);
if ($this->connection->connect_error) {
echo "Connection failed: " . $this->connection->connect_error;
exit;
}
$this->connection->query("SET NAMES 'utf8'");
}
private function safeQuery(&$sql, $data){
foreach ($data as $key=>$value){
$value = $this->connection->real_escape_string($value);
$value = "'$value'";
$sql = str_replace(":$key", $value, $sql);
}
return $this->connection->query($sql);
}
public function first($sql, $data = array()){
$records = $this->query($sql, $data);
if ($records == null){
return null;
}
return $records[0];
}
public function modify($sql, $data = array()){
$result = $this->safeQuery($sql, $data);
if (!$result) {
echo "Query: " . $sql . " failed due to " . mysqli_error($this->connection);
exit;
}
return $result;
}
public function insert($sql, $data = array()){
$result = $this->safeQuery($sql, $data);
if (!$result) {
echo "Query: " . $sql . " failed due to " . mysqli_error($this->connection);
exit;
}
return $result;
}
public function query($sql, $data = array()){
$result = $this->safeQuery($sql, $data);
if (!$result) {
echo "Query: " . $sql . " failed due to " . mysqli_error($this->connection);
exit;
}
$records = array();
if ($result->num_rows == 0) {
return null;
}
while($row = $result->fetch_assoc()) {
$records[] = $row;
}
return $records;
}
public function connection(){
return $this->connection;
}
public function close(){
$this->connection->close();
}
}