summaryrefslogtreecommitdiff
path: root/includes/Database.php
blob: 61fbbb1b8deb72d22e7fb4e1e659efa6871761fb (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
71
72
73
74
75
76
77
78
79
80
81
82
<?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
	{
		$result = array();

		if ($types == "") {
			// No types were provided, preparing a statement is not necessary
			$db_result = mysqli_query($this->sql_connection, $sql);
		} else {
			$stmt = mysqli_stmt_init($this->sql_connection);

			if (!mysqli_stmt_prepare($stmt, $sql)) {
				trigger_error('Internal error: ' . mysqli_error($this->sql_connection));
				return $result;
			}

			mysqli_stmt_bind_param($stmt, $types, ...$vars);
			mysqli_stmt_execute($stmt);

			$db_result = mysqli_stmt_get_result($stmt);

			mysqli_stmt_close($stmt);
		}

		if (!$db_result) {
			return $result;
		}

		if (mysqli_num_rows($db_result) > 0) {
			while ($row = mysqli_fetch_assoc($db_result)) {
				array_push($result, $row);
			}
		}

		mysqli_free_result($db_result);

		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);
	}
}