From df00b63f35477a7c8f72c0223ac847c99b958359 Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Wed, 14 Feb 2024 09:15:24 +0000 Subject: [PATCH] feat: INSERT specified columns by passing assoc array to method (#33) * feat: named columns for INSERT statements * feat(doc): add assoc array ref to README --- README.md | 4 +++- src/MySQL.php | 8 +++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index afc4aa4..fc121e9 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,9 @@ $coffee = MySQL->for("beverages")->limit(1)->flatten()->select(["beverage_name", # INSERT -Use `MySQL->insert()` to append a new row to a database table +Use `MySQL->insert()` to append a new row to a database table. + +Passing a sequential array to `insert()` will assume that you wish to insert data for all defined columns in the table. Pass an associative array of `[column_name => value]` to INSERT data for specific columns (assuming the other columns have a [DEFAULT](https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html) value defined). ```php MySQL->insert( diff --git a/src/MySQL.php b/src/MySQL.php index 7919cc3..6cba7b1 100644 --- a/src/MySQL.php +++ b/src/MySQL.php @@ -279,6 +279,12 @@ throw new Exception("Values length does not match columns in model"); } + /* + Use array keys from $values as columns to insert if array is associative. + Treat statement as an all-columns INSERT if the $values array is sequential. + */ + $columns = !array_is_list($values) ? "(" . implode(",", array_keys($values)) . ")" : ""; + // Convert booleans to tinyint $values = self::filter_booleans($values); @@ -286,7 +292,7 @@ $values_stmt = implode(",", array_fill(0, count($values), "?")); // Interpolate components into an SQL INSERT statement and execute - $sql = "INSERT INTO {$this->table} VALUES ({$values_stmt})"; + $sql = "INSERT INTO {$this->table} {$columns} VALUES ({$values_stmt})"; return $this->execute_query($sql, self::to_list_array($values)); }