I have a PHP function that do batch insertion into a MYSQL table. The function take input parameter as an array, it then loop thru the array to build the insert query like this:
public function batchInsert($values){
$nbValues = count($values);
$sql = 'INSERT INTO vouchers (`code`,`pin`,`owner_id`,`value`,`description`,`expire_date`,`lifetime`) VALUES ';
for ($i=0; $i < $nbValues; $i++) {
$sql .= '(:col1_'.$i.', :col2_'.$i.', :col3_'.$i.', :col4_'.$i.', :col5_'.$i.', :col6_'.$i.', :col7_'.$i.')';
if ($i !== ($nbValues-1))
$sql .= ',';
}
$command = Yii::app()->db->createCommand($sql);
for ($i=0; $i < $nbValues; $i++) {
$command->bindParam(':col1_'.$i, $values[$i]['code'], PDO::PARAM_STR);
$command->bindValue(':col2_'.$i, sha1($values[$i]['pin']), PDO::PARAM_STR);
$command->bindParam(':col3_'.$i, $values[$i]['owner_id'], PDO::PARAM_INT);
$command->bindParam(':col4_'.$i, $values[$i]['value'], PDO::PARAM_INT);
$command->bindParam(':col5_'.$i, $values[$i]['description'], PDO::PARAM_STR);
$command->bindParam(':col6_'.$i, $values[$i]['expire_date'], PDO::PARAM_STR);
$command->bindParam(':col7_'.$i, $values[$i]['lifetime'], PDO::PARAM_INT);
}
return $command->execute();
}
If the input array has 1K elements, the building of this sql query would take quite a large time. I believe this is caused by the way $sql variable is reconstructed after every loop. Is there any better way that you could suggest for me to optimise this? Thank you!
P/S: At the end of this batch insertion, I need to export all generated vouchers to an Excel file. Hence, if I built one single query and if the query was successful then the export function is called. By doing many seperate insertions, I cannot keep track of which one is inserted and which one is not (e.g. voucher code is unique, randomly generated and may have a chance of colliding). That's why I need a single query (or am I wrong?).
for.for. It's two sequentialfors The if statement is inline, but has the closing for bracket where the ifs closing bracket should be.