From 72315b403096cb991060ef139292a74d037c2132 Mon Sep 17 00:00:00 2001 From: patrickzerhusen Date: Fri, 17 Apr 2026 16:36:16 +0200 Subject: [PATCH] added database helper including JSON response and input validation utilities --- api/db.php | 90 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) diff --git a/api/db.php b/api/db.php index e69de29..e976618 100644 --- a/api/db.php +++ b/api/db.php @@ -0,0 +1,90 @@ + $message], $status_code); +} + + +// --------------------------------------------------------------------- +// Validate Required Fields +// Checks if all specified Fields exist in the given Data Array and are +// non-empty. Returns an Array of missing Field Names, or an empty +// Array if all Fields are present. +// --------------------------------------------------------------------- +function validate_required($data, $fields) { + $missing = []; + + foreach ($fields as $field) { + if (!isset($data[$field]) || trim($data[$field]) === '') { + $missing[] = $field; + } + } + + return $missing; +} + + +// --------------------------------------------------------------------- +// Get POST Input +// Reads and trims all POST Parameters. Returns an associative Array. +// Falls back to JSON Request Body if no POST Data is present +// (for Clients that send JSON instead of Form Data). +// --------------------------------------------------------------------- +function get_input() { + // Check for standard POST Form Data first + if (!empty($_POST)) { + return array_map('trim', $_POST); + } + + // Fall back to JSON Request Body + $json = file_get_contents('php://input'); + $data = json_decode($json, true); + + if (is_array($data)) { + return array_map('trim', $data); + } + + return []; +} + + +// --------------------------------------------------------------------- +// Get PDO Connection +// Returns the PDO Instance created in init.php. Wrapped in a Function +// to avoid global Variable Dependencies in Endpoint Files. +// --------------------------------------------------------------------- +function get_db() { + global $pdo; + + if (!$pdo) { + error_response('Database Connection failed.', 500); + } + + return $pdo; +} \ No newline at end of file