/
mysqli.php
86 lines (71 loc) · 2.03 KB
/
mysqli.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
<?php
namespace DB;
class MySQLi {
private $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306') {
try {
$mysqli = @new \MySQLi($hostname, $username, $password, $database, $port);
} catch (\mysqli_sql_exception $e) {
throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname . '!');
}
if (!$mysqli->connect_errno) {
mysqli_report(MYSQLI_REPORT_ERROR);
$this->connection = $mysqli;
// $this->connection->report_mode = MYSQLI_REPORT_ERROR;
$this->connection->set_charset('utf8');
$this->connection->query("SET SESSION sql_mode = 'NO_ZERO_IN_DATE,NO_ENGINE_SUBSTITUTION'");
} else {
throw new \Exception('Error: Could not make a database link using ' . $username . '@' . $hostname . '!');
}
}
public function query($sql) {
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = [];
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : [];
$result->rows = $data;
$query->close();
unset($data);
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value) {
return $this->connection->real_escape_string(($value===null) ? '' : $value);
}
public function countAffected() {
return $this->connection->affected_rows;
}
public function getLastId() {
return $this->connection->insert_id;
}
public function isConnected() {
if ($this->connection) {
return $this->connection->ping();
} else {
return false;
}
}
/**
* __destruct
*
* Closes the DB connection when this object is destroyed.
*
*/
public function __destruct() {
if ($this->connection) {
$this->connection->close();
$this->connection = '';
}
}
}