From 13720e772e2d25da2f43629e6bb987cc973c7f28 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Thu, 2 Nov 2023 11:24:20 +0100 Subject: [PATCH] feat: accept CSV string as columns for `select()` (#16) * feat: accept CSV string as columns for select() * feat(doc): add string doc for select to README --- README.md | 9 +++++---- src/MySQL.php | 5 ++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 19871c7..9178ecd 100644 --- a/README.md +++ b/README.md @@ -59,13 +59,13 @@ $db = new MySQL($host, $user, $pass, $db); # SELECT -Use `MySQL->select()` to retrieve columns from a database table +Use `MySQL->select()` to retrieve columns from a database table. + +Pass an associative array of strings, CSV string, or null to this method to filter columns. ```php $db->select( - // Sequential array of string with column names to retrieve - // Or null to retrieve a bool if rows were matched - ?array $columns + array|string|null $columns ): array|bool; // Returns array of arrays for each row, or bool if no columns were defined ``` @@ -75,6 +75,7 @@ In most cases you probably want to select with a constraint. Chain the [`where() ### Example ```php $beverages = $db->for("beverages")->select(["beverage_name", "beverage_size"]); // SELECT beverage_name, beverage_size FROM beverages +$beverages = $db->for("beverages")->select("beverage_name, beverage_size"); // SELECT beverage_name, beverage_size FROM beverages ``` ``` [ diff --git a/src/MySQL.php b/src/MySQL.php index 4791094..e62c7af 100644 --- a/src/MySQL.php +++ b/src/MySQL.php @@ -136,9 +136,12 @@ /* ---- */ // Create Prepared Statament for SELECT with optional WHERE filters - public function select(?array $columns = null): array|bool { + public function select(array|string|null $columns = null): array|bool { $this->throw_if_no_table(); + // Create array of columns from CSV + $columns = is_array($columns) ? $columns : explode(",", $columns); + // Filter columns that aren't in the model if defiend if ($columns && $this->model) { $columns = $this->in_model($columns);