forked from froxlor/Froxlor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB.mysqli.class.php
89 lines (78 loc) · 2.9 KB
/
DB.mysqli.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
<?php
class DB {
private $db;
private $credentials;
private $queries = array();
public function __construct($host, $user, $pw, $db=null) {
$this->credentials = array('host' => $host, 'user' => $user, 'pw' => $pw, 'db' => $db);
$this->connect();
}
private function connect() {
$tries = 0;
do {
$this->db = $this->realConnect();
if (!$this->db) {
echo "Could not connect. Retrying 12 times (try=$tries)\n";
sleep(5);
}
$tries++;
if ($tries > 12) break;
} while ($this->db == false);
if (!$this->db) {
echo "Could not establish a database connection - cancelling\n";
echo mysqli_error($this->db);
return false;
}
if ($this->credentials['db'] != null) {
return mysqli_select_db($this->db, $this->credentials['db']) or die(mysqli_error($this->db));
}
return true;
}
private function realConnect() {
return mysqli_connect($this->credentials['host'], $this->credentials['user'], $this->credentials['pw']);
}
public function disconnect() {
mysqli_close($this->db);
$this->db = false;
}
public function addQuery($sql) {
$this->queries[] = $sql;
}
public function clearMultiQuery() {
$this->queries = array();
}
public function multiQuery() {
// file_put_contents("db-sql.log", implode(";", $this->queries) . "\n", FILE_APPEND);
$success = mysqli_multi_query($this->db, implode(";", $this->queries));
$this->clearMultiQuery();
return $success;
}
public function query($sql, $returnRes = false) {
// file_put_contents("db-sql.log", $sql . "\n", FILE_APPEND);
if (!$this->db) {
if (!$this->connect()) {
echo "Could not execute query. connect() failed\n";
return false;
}
}
$res = mysqli_query($this->db, $sql);
if ((is_object($res) && $returnRes) || !is_object($res)) {
return $res;
} else {
$data = array();
while ($row = mysqli_fetch_assoc($res)) {
$data[] = $row;
}
}
return $data;
}
public function escape($n) {
if (!$this->db) {
$this->connect();
}
return mysqli_real_escape_string($this->db, $n);
}
public function __destruct() {
mysqli_close($this->db);
}
}