From 978d6461c5d40647c1efcc2965d2f55ea1d43025 Mon Sep 17 00:00:00 2001 From: Aaron van Geffen Date: Mon, 12 Jun 2023 12:49:22 +0200 Subject: [PATCH] Database: add fetch_object, queryObject, queryObjects methods --- models/Database.php | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/models/Database.php b/models/Database.php index 226cd74..8bc0fad 100644 --- a/models/Database.php +++ b/models/Database.php @@ -59,6 +59,14 @@ class Database return mysqli_fetch_assoc($resource); } + /** + * Fetches a row from a given recordset, encapsulating into an object. + */ + public function fetch_object($resource, $class) + { + return mysqli_fetch_object($resource, $class); + } + /** * Fetches a row from a given recordset, using numeric keys. */ @@ -341,6 +349,41 @@ class Database return $db_string; } + /** + * Executes a query, returning an object of the row it returns. + */ + public function queryObject($class, $db_string, $db_values = []) + { + $res = $this->query($db_string, $db_values); + + if (!$res || $this->num_rows($res) == 0) + return null; + + $object = $this->fetch_object($res, $class); + $this->free_result($res); + + return $object; + } + + /** + * Executes a query, returning an array of objects of all the rows returns. + */ + public function queryObjects($class, $db_string, $db_values = []) + { + $res = $this->query($db_string, $db_values); + + if (!$res || $this->num_rows($res) == 0) + return []; + + $rows = []; + while ($object = $this->fetch_object($res, $class)) + $rows[] = $object; + + $this->free_result($res); + + return $rows; + } + /** * Executes a query, returning an array of all the rows it returns. */