From 38fe8e5b8282f1369a73c1a1b96172386c05a71c Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Sun, 24 Dec 2023 19:48:36 +0100 Subject: [PATCH] feat(refactor): implement mysqli->execute_query() (#22) --- src/DatabaseDriver.php | 63 ++---------------------------------------- 1 file changed, 2 insertions(+), 61 deletions(-) diff --git a/src/DatabaseDriver.php b/src/DatabaseDriver.php index 79e2460..111c212 100644 --- a/src/DatabaseDriver.php +++ b/src/DatabaseDriver.php @@ -13,68 +13,9 @@ parent::__construct(...func_get_args()); } - // Bind SQL statements - private function bind_params(mysqli_stmt &$stmt, mixed $params): bool { - // Convert single value parameter to array - $params = is_array($params) ? $params : [$params]; - if (empty($params)) { - return true; - } - - // Concatenated string with types for each parameter - $types = ""; - - // Convert PHP primitves to SQL primitives - foreach ($params as $param) { - switch (gettype($param)) { - case "integer": - case "double": - case "boolean": - $types .= "i"; - break; - - case "string": - case "array": - case "object": - $types .= "s"; - break; - - default: - $types .= "b"; - break; - } - } - - return $stmt->bind_param($types, ...$params); - } - - // Execute an SQL query with a prepared statement - private function run_query(string $sql, mixed $params = null): mysqli_result|bool { - $stmt = $this->prepare($sql); - - // Bind parameters if provided - if ($params !== null) { - $this->bind_params($stmt, $params); - } - - // Execute statement and get retrieve changes - $query = $stmt->execute(); - $res = $stmt->get_result(); - - // Return true if an INSERT, UPDATE or DELETE was sucessful (no rows returned) - if (!empty($query) && empty($res)) { - return true; - } - - // Return mysqli_result object - return $res; - } - - /* ---- */ - // Execute SQL query with optional prepared statement and return array of affected rows public function exec(string $sql, mixed $params = null): array { - $query = $this->run_query($sql, $params); + $query = $this->execute_query($sql, $params); $res = []; // Fetch rows into sequential array @@ -87,7 +28,7 @@ // Execute SQL query with optional prepared statement and return true if query was successful public function exec_bool(string $sql, mixed $params = null): bool { - $query = $this->run_query($sql, $params); + $query = $this->execute_query($sql, $params); return gettype($query) === "boolean" // Type is already a bool, so return it as is