From 17e9c15e9a72d37bcb005eb4b585e2d63ff44c4b Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Wed, 14 Feb 2024 01:15:47 +0100 Subject: [PATCH] feat: named columns for INSERT statements --- src/MySQL.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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)); }