blob: cdaa0f8cf3a645a6051c8aa83665b686c1084371 (
plain)
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
|
<?php
class Database
{
private static $instance = null;
private $sql_connection;
private function __construct()
{
$config = parse_ini_file('config.ini', true)['mysql_credentials'];
$db_server = $config['server'];
$db_user = $config['user'];
$db_pass = $config['password'];
$db_database = $config['database'];
$this->sql_connection = mysqli_connect($db_server, $db_user, $db_pass, $db_database);
if (!$this->sql_connection) {
trigger_error("Database connection error: " . mysqli_connect_error());
}
}
public static function get()
{
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function query(string $sql, string $types = "", ...$vars): array
{
$stmt = mysqli_stmt_init($this->sql_connection);
if (!mysqli_stmt_prepare($stmt, $sql)) {
trigger_error('Could not create post due to internal error: ' . mysqli_error($this->sql_connection));
}
mysqli_stmt_bind_param($stmt, $types, ...$vars);
mysqli_stmt_execute($stmt);
$result = array();
$db_result = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($db_result) > 0) {
while ($row = mysqli_fetch_assoc($db_result)) {
array_push($result, $row);
}
}
mysqli_free_result($db_result);
mysqli_stmt_close($stmt);
return $result;
}
/**
* Returns the auto generated ID of the last query.
* This function is just a wrapper for mysqli_insert_id.
* In the future, it might be better to return different
* values in the query function depending on the type of
* SQL query.
*/
public function get_last_id()
{
return mysqli_insert_id($this->sql_connection);
}
}
|