Skip to content

Commit 7cd05ca

Browse files
authored
Merge pull request #7 from joshcam/master
q
2 parents 64b5a57 + 8305412 commit 7cd05ca

File tree

4 files changed

+124
-4
lines changed

4 files changed

+124
-4
lines changed

MysqliDb.php

+42
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,48 @@ public function insert($tableName, $insertData)
679679
return $this->_buildInsert($tableName, $insertData, 'INSERT');
680680
}
681681

682+
/**
683+
* Insert method to add several rows at once
684+
*
685+
* @param string $tableName The name of the table.
686+
* @param array $multiInsertData Two-dimensinal Data-array containing information for inserting into the DB.
687+
* @param array $dataKeys Optinal Table Key names, if not set in insertDataSet.
688+
*
689+
* @return bool|array Boolean indicating the insertion failed (false), else return id-array ([int])
690+
*/
691+
public function insertMulti($tableName, array $multiInsertData, array $dataKeys = null)
692+
{
693+
// only auto-commit our inserts, if no transaction is currently running
694+
$autoCommit = (isset($this->_transaction_in_progress) ? !$this->_transaction_in_progress : true);
695+
$ids = array();
696+
697+
if($autoCommit) {
698+
$this->startTransaction();
699+
}
700+
701+
foreach ($multiInsertData as $insertData) {
702+
if($dataKeys !== null) {
703+
// apply column-names if given, else assume they're already given in the data
704+
$insertData = array_combine($dataKeys, $insertData);
705+
}
706+
707+
$id = $this->insert($tableName, $insertData);
708+
if(!$id) {
709+
if($autoCommit) {
710+
$this->rollback();
711+
}
712+
return false;
713+
}
714+
$ids[] = $id;
715+
}
716+
717+
if($autoCommit) {
718+
$this->commit();
719+
}
720+
721+
return $ids;
722+
}
723+
682724
/**
683725
* Replace method to add new row
684726
*

index.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ function action_mod () {
118118
<input type=text name='lastName' required placeholder='Last Name' value='<?php echo $data['lastName']?>'>
119119
<input type=password name='password' placeholder='Password'>
120120
<input type=submit value='New User'></td>
121-
<form>
121+
</form>
122122
</table>
123123
</center>
124124
</body>

readme.md

+38-1
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,43 @@ $db->onDuplicate($updateColumns, $lastInsertId);
144144
$id = $db->insert ('users', $data);
145145
```
146146

147+
Insert multiple datasets at once
148+
```php
149+
$data = Array(
150+
Array ("login" => "admin",
151+
"firstName" => "John",
152+
"lastName" => 'Doe'
153+
),
154+
Array ("login" => "other",
155+
"firstName" => "Another",
156+
"lastName" => 'User',
157+
"password" => "very_cool_hash"
158+
)
159+
);
160+
$ids = $db->insertMulti('users', $data);
161+
if(!$ids) {
162+
echo 'insert failed: ' . $db->getLastError();
163+
} else {
164+
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
165+
}
166+
```
167+
168+
If all datasets only have the same keys, it can be simplified
169+
```php
170+
$data = Array(
171+
Array ("admin", "John", "Doe"),
172+
Array ("other", "Another", "User")
173+
);
174+
$keys = Array("login", "firstName", "lastName");
175+
176+
$ids = $db->insertMulti('users', $data, $keys);
177+
if(!$ids) {
178+
echo 'insert failed: ' . $db->getLastError();
179+
} else {
180+
echo 'new users inserted with following id\'s: ' . implode(', ', $ids);
181+
}
182+
```
183+
147184
### Replace Query
148185
<a href='https://dev.mysql.com/doc/refman/5.0/en/replace.html'>Replace()</a> method implements same API as insert();
149186

@@ -713,7 +750,7 @@ else
713750
echo 'Update failed. Error: '. $db->getLastError();
714751
```
715752

716-
### Query exectution time benchmarking
753+
### Query execution time benchmarking
717754
To track query execution time setTrace() function should be called.
718755
```php
719756
$db->setTrace (true);

tests/mysqliDbTests.php

+43-2
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,8 @@ function createTable ($name, $data) {
396396
}
397397
unset ($cnt);
398398

399-
$data = $db->get('users');
400-
if (count($data) != 3) {
399+
$users = $db->get('users');
400+
if (count($users) != 3) {
401401
echo "copy with subquery data count failed";
402402
exit;
403403
}
@@ -444,6 +444,47 @@ function createTable ($name, $data) {
444444
exit;
445445
}
446446

447+
$expectedIDs = [
448+
'users' => [5, 6, 7],
449+
'products' => [6,7,8,9,10],
450+
];
451+
452+
// multi-insert test with autoincrement
453+
foreach ($data as $name => $datas) {
454+
455+
// remove previous entries to ensure avoiding PRIMARY-KEY collisions here
456+
$db->delete($name);
457+
458+
// actual insertion test
459+
$ids = $db->insertMulti($name, $datas);
460+
461+
// check results
462+
if(!$ids) {
463+
echo "failed to multi-insert: ".$db->getLastQuery() ."\n". $db->getLastError();
464+
exit;
465+
} elseif($ids !== $expectedIDs[$name]) {
466+
pretty_print($ids);
467+
echo "multi-insert succeeded, but unexpected id's: ".$db->getLastQuery() ."\n". $db->getLastError();
468+
exit;
469+
}
470+
}
471+
472+
// skip last user here, since it has other keys than the others
473+
unset($data['users'][2]);
474+
475+
// multi-insert test with autoincrement and overriding column-names
476+
foreach ($data as $name => $datas) {
477+
478+
// remove previous entries to ensure avoiding PRIMARY-KEY collisions here
479+
$db->delete($name);
480+
481+
// actual insertion test
482+
if(!$db->insertMulti($name, $datas, array_keys($datas[0]))) {
483+
echo "failed to multi-insert: ".$db->getLastQuery() ."\n". $db->getLastError();
484+
exit;
485+
}
486+
}
487+
447488
///
448489
//TODO: insert test
449490
$db->delete("users");

0 commit comments

Comments
 (0)