mirror of
https://codeberg.org/vlw/php-mysql.git
synced 2025-09-13 16:23:42 +02:00
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
This commit is contained in:
parent
17fa248edb
commit
df00b63f35
2 changed files with 10 additions and 2 deletions
|
@ -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(
|
||||
|
|
|
@ -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));
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue