Why does this SQLite transaction with prepared sta

2019-09-05 19:01发布

问题:

I'm trying to combine an SQLite transaction and prepared statement to get the best insert speed for thousands of records. However, all the inserted lines are empty.

Printing the variables before inserting shows that they have the correct data and there are no errors.

$db->beginTransaction();
$insert_stmt = $db->prepare("INSERT INTO `table` VALUES (:id, :value2, :value3, :value4)");
$insert_stmt->bindValue(":id", $id);
$insert_stmt->bindValue(":value2", $value2);
$insert_stmt->bindValue(":value3", $value3);
$insert_stmt->bindValue(":value4", $value4);

foreach ($records as $record)
{
  $id = $record["id"];
  $value2 = $record["value2"];
  $value3 = $record["value3"];
  $value4 = $record["value4"];
  $insert_stmt->execute();
  print_r($db->errorInfo()); // print errors
}

$db->commit();
  1. What's wrong with the code?
  2. How can I get better output? Printing the prepared statements before executing for example, to see if there's something wrong with it.

回答1:

You have to put the bindValue calls into your loop.

The values get copied into the statement when you execute bindValue. Whatever happens to the variable you used to do that afterwards does not matter.