From 7c3f2e348c015ea93563d866f89ec8cea9159ea0 Mon Sep 17 00:00:00 2001 From: cflip <36554078+cflip@users.noreply.github.com> Date: Sat, 24 Apr 2021 09:40:20 -0600 Subject: Refactoring part 2 Starting to move some functionality such as the session and database connection into singleton classes to manage them. Functions for modifying posts and threads are being put in one place as well. --- includes/Database.php | 39 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) (limited to 'includes/Database.php') diff --git a/includes/Database.php b/includes/Database.php index 3308e4c..cdaa0f8 100644 --- a/includes/Database.php +++ b/includes/Database.php @@ -21,7 +21,7 @@ class Database } } - public static function get(): ?Database + public static function get() { if (self::$instance == null) { self::$instance = new Database(); @@ -30,8 +30,41 @@ class Database return self::$instance; } - public function query(string $sql) + public function query(string $sql, string $types = "", ...$vars): array { - mysqli_query($this->sql_connection, $sql); + $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); } } \ No newline at end of file -- cgit v1.2.3