-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.php
106 lines (88 loc) · 2.29 KB
/
database.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
<?php
require_once(dirname(__FILE__) . '/../../config/database.php');
/*Please generate your database config file and change the include path above by yourself:
<?php
define('DB_HOST', 'localhost');
define('DB_PORT', '');
define('DB_USERNAME', 'db_user');
define('DB_PASSWORD', 'db_pass');
define('DB_NAME', 'db_name');
define('DB_CHARSET', 'utf8');*/
class Database {
private $connection;
function __construct() {
if (!$this->connection) {
$this->connection = new mysqli(
DB_HOST ? DB_HOST : null,
DB_USERNAME ? DB_USERNAME : null,
DB_PASSWORD ? DB_PASSWORD : null,
DB_NAME ? DB_NAME : null,
DB_PORT ? DB_PORT : null
);
$this->connection->set_charset(DB_CHARSET ? DB_CHARSET : 'utf8');
}
}
function __destruct() {
if ($this->connection) {
$this->connection->close();
}
}
/*
* Execute sql without result
*/
public function execute($sql) {
return $this->connection->query($sql);
}
/*
* Execute sql and returns result
* result is array of entries
* entry is associated array with $field => $value
*/
public function query($sql) {
$result = $this->connection->query($sql);
$arrResult = array();
while ($entry = $result->fetch_assoc()) {
array_push($arrResult, $entry);
}
return $arrResult;
}
/*
* Execute sql and returns result
* result is associated array with $keyField => $entry of entries
* entry is associated array with $field => $value
*/
public function queryAssoc($sql, $keyField) {
$result = $this->connection->query($sql);
$arrResult = array();
while ($entry = $result->fetch_assoc()) {
$arrResult[$entry[$keyField]] = $entry;
}
return $arrResult;
}
/*
* Execute sql and return an array of entry
*/
public function queryEntry($sql) {
$result = $this->connection->query($sql);
return $result->fetch_assoc();
}
/*
* Execute sql and returns array of all entrys' first value
*/
public function queryValues($sql) {
$result = $this->connection->query($sql);
$arrResult = array();
while ($entry = $result->fetch_array()) {
array_push($arrResult, $entry[0]);
}
return $arrResult;
}
/*
* Execute sql and returns the first value of the first entry
*/
public function queryValue($sql) {
$result = $this->connection->query($sql);
$entry = $result->fetch_array();
return $entry[0];
}
}