I want to insert 20 values at once via PHP Data Objects. At the moment I'm doing it this way, it seems very ugly:
$stmt = $this->pdo->prepare("INSERT INTO <tablename> (`uid`, `mid`, `status`)
VALUES (:uid, :mid1, :status), (:uid, :mid2, :status),
(:uid, :mid3, :status), (:uid, :mid4, :status),
(:uid, :mid5, :status), ... and so on ...");
$stmt->bindParam(':uid', $this->uid);
$random_mid = array_rand(range(1,20), 5);
$ref = new Mooney($random_mid[0]);
$myMid1 = $ref->getMid();
$stmt->bindParam(':mid1', $myMid1);
$ref = new Mooney($random_mid[1]);
$myMid2 = $ref->getMid();
$stmt->bindParam(':mid2', $myMid2);
$ref = new Mooney($random_mid[2]);
$myMid3 = $ref->getMid();
$stmt->bindParam(':mid3', $myMid3);
... and so on ...
$status = 'open'; // default starting value of status
$stmt->bindParam(':status', $status);
$stmt->execute();
Is there a better solution by using a for-loop or so? Hope you can provide a better solution / more beautiful solution. Thanks for your time and help!
EDIT 1: Now thanks to @Jurik the code works and look like this:
private function insertValuesAtOnce() {
$stmt = $this->pdo->prepare('INSERT INTO `<tablename>` (`uid`, `mid`, `status`) VALUES (:UID, :MID, :STATUS)');
$random_mid = $this->UniqueRandomNumbersWithinRange(1, 20, 7);
require_once('<some path>');
$status = 'open';
foreach($random_mid AS $val){
$ref = new Mooney($val);
$myMid = $ref->getMid();
$stmt->execute(array(
':UID' => $this->uid,
':MID' => $myMid,
':STATUS' => $status
));
}
}
But it seems to me, that this is not a "insert many rows at once" but more "insert a single row multiple times"
EDIT 2: Because it does not seem to be possible to insert all values at once, I will use the solution to insert them row by row, but wrapping it into a transaction! This improved the runtime from 0,3915548324585 sec/serialize to 0,074591159820557 sec/serialize.
private function insertValuesAtOnce() {
$stmt = $this->pdo->prepare('INSERT INTO `<tablename>` (`uid`, `mid`, `status`) VALUES (:UID, :MID, :STATUS)');
$random_mid = $this->UniqueRandomNumbersWithinRange(1, 20, 7);
require_once('<some path>');
$status = 'open';
// Beginn Transaction (ACID)
$this->pdo->beginTransaction();
foreach($random_mid AS $val){
$ref = new Mooney($val);
$myMid = $ref->getMid();
$stmt->execute(array(
':UID' => $this->uid,
':MID' => $myMid,
':STATUS' => $status
));
}
// End Transaction (ACID)
$this->pdo->commit();
}
getMid()gets data from database that needs a data base before anything else inserts into db?beginTransaction. Otherwisecommitdoesn't make sense. Don't forgettrollbackon db error. So you won't have inconsistent data. Good job :)