lollipop

A PHP-framework
Log | Files | Refs

commit 5a9f53c823866ac22a8b37a08e37476c12d3c9af
parent fae9d11f34cc60b1852740158cea5bd0426655d6
Author: Friedel Schon <[email protected]>
Date:   Tue, 11 Apr 2023 13:25:14 +0200

SQLDatabase::where()

Diffstat:
MLollipop/SQLDatabase.php | 35+++++++++++++++++++++++++++++++++++
Mtest_orm.php | 8+++-----
2 files changed, 38 insertions(+), 5 deletions(-)

diff --git a/Lollipop/SQLDatabase.php b/Lollipop/SQLDatabase.php @@ -19,6 +19,41 @@ namespace Lollipop { return $cls; } + function where(string $table_name, array $vars) + { + if (!sizeof($vars)) { + return []; + } + $cls = new $table_name($this); + + $sql = "SELECT {$cls->get_primary()} FROM {$cls->get_table()} WHERE "; + $params = []; + + $i = 0; + foreach ($vars as $key => $value) { + if ($i > 0) { + $sql .= ' AND '; + } + $sql .= " $key = ?"; + $params[] = $value; + $i++; + } + + $stmt = $this->conn->prepare($sql); + $stmt->execute($params); + $result = $stmt->get_result(); + + if (!$result || $result->num_rows == 0) { + return []; + } + + $objects = []; + while ($row = $result->fetch_assoc()) { + $objects[] = $this->get($table_name, $row[$cls->get_primary()]); + } + return $objects; + } + function all(string $table_name) { $cls = new $table_name($this); diff --git a/test_orm.php b/test_orm.php @@ -4,8 +4,6 @@ include "utils/autoloader.php"; $db = new Lollipop\SQLDatabase("86.92.67.21", "friedel", "hailiwa", "lollipop"); -$u = $db->all(User::class); +$u = $db->where(User::class, ["fname" => "Harald"]); -foreach ($u as $c) { - var_dump($c); -} -\ No newline at end of file +var_dump($u); +\ No newline at end of file