Aggregate.php
9 months ago
CRUD.php
1 year ago
FromClause.php
4 years ago
GroupByStatement.php
4 years ago
HavingClause.php
3 years ago
InsertInto.php
1 year ago
JoinClause.php
4 years ago
LimitStatement.php
4 years ago
MetaQuery.php
3 years ago
OffsetStatement.php
4 years ago
OrderByStatement.php
1 year ago
SelectStatement.php
4 years ago
TablePrefix.php
4 years ago
UnionOperator.php
4 years ago
WhereClause.php
3 years ago
InsertInto.php
56 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\QueryBuilder\Concerns; |
| 4 | |
| 5 | use Give\Framework\Database\DB; |
| 6 | |
| 7 | /** |
| 8 | * @since 4.0.0 |
| 9 | */ |
| 10 | trait InsertInto |
| 11 | { |
| 12 | /** |
| 13 | * @since 4.0.0 |
| 14 | */ |
| 15 | public function getInsertIntoSQL($data, $format): string |
| 16 | { |
| 17 | $sql = 'INSERT INTO ' . $this->getTable() |
| 18 | . sprintf(' (%s) ', implode(',', array_keys($data[0]))) |
| 19 | . 'VALUES '; |
| 20 | |
| 21 | foreach ($data as $row) { |
| 22 | $sql .= DB::prepare( |
| 23 | sprintf('(%s),', implode(',', $format ?? $this->getInsertIntoRowValuesFormat($row))), |
| 24 | $row |
| 25 | ); |
| 26 | } |
| 27 | |
| 28 | return rtrim($sql, ','); |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Get values format used by DB::prepare() |
| 33 | * |
| 34 | * @since 4.0.0 |
| 35 | * |
| 36 | * @param array $data |
| 37 | * |
| 38 | * @return array |
| 39 | */ |
| 40 | private function getInsertIntoRowValuesFormat(array $data): array |
| 41 | { |
| 42 | return array_map(function ($value) { |
| 43 | if (is_int($value)) { |
| 44 | return '%d'; |
| 45 | } |
| 46 | |
| 47 | if (is_float($value)) { |
| 48 | return '%f'; |
| 49 | } |
| 50 | |
| 51 | return '%s'; |
| 52 | }, $data); |
| 53 | } |
| 54 | |
| 55 | } |
| 56 |