-
Notifications
You must be signed in to change notification settings - Fork 2
/
db.php
90 lines (79 loc) · 2.83 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
<?php
class Db {
// The database connection
protected static $connection;
/**
* Connect to the database
*
* @return bool false on failure / mysqli MySQLi object instance on success
*/
public function connect() {
// Try and connect to the database
if(!isset(self::$connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file(dirname(__FILE__).'/config.ini.php');
self::$connection = new mysqli('localhost', $config['username'], $config['password'], $config['dbname']);
}
// If connection was not successful, handle the error
if(self::$connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return false;
}
self::$connection->set_charset("utf8");
return self::$connection;
}
/**
* Query the database
*
* @param $query The query string
* @return mixed The result of the mysqli::query() function
*/
public function query($query) {
// Connect to the database
$connection = $this -> connect();
// Query the database
$result = $connection -> query($query);
return $result;
}
/**
* Fetch rows from the database (SELECT query)
*
* @param $query The query string
* @return bool False on failure / array Database rows on success
*/
public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function selectOne($query) {
$result = $this->select($query);
return $result[0];
}
/**
* Fetch the last error from the database
*
* @return string Database error message
*/
public function error() {
$connection = $this -> connect();
return $connection -> error;
}
/**
* Quote and escape value for use in a database query
*
* @param string $value The value to be quoted and escaped
* @return string The quoted and escaped string
*/
public function quote($value) {
$connection = $this -> connect();
return "'" . $connection -> real_escape_string($value) . "'";
}
}
?>