我目前正在尝试优化脚本,它基本上从一个表中选择大量数据,然后将大量数据插入到另一个表中。以前我有这样的代码:
$res = $db->prepare($selectQry);
$tres = $db->prepare($insertQry);
foreach($fooData as $foo){
$res->bindParam('foo', $foo, PDO::PARAM_INT);
$db->beginTransaction();
$res->execute();
foreach($res as $row){
$tres->bindParam('foo', $row['foo'], PDO::PARAM_INT);
$tres->bindParam('bar', $row['bar'], PDO::PARAM_INT);
$tres->execute();
}
$db->commit();
}
现在我在stackoverflow上找到了这个很棒的答案:https://stackoverflow.com/a/19107074/2015253 并且想要尝试将参数绑定移动到循环外部。这是我的尝试:
$res = $db->prepare($selectQry);
$tres = $db->prepare($insertQry);
$foo = null;
$row = null; // also tried $row = []; and $row = ['foo' => null, 'bar' => null];
$res->bindParam('foo', $foo, PDO::PARAM_INT);
$tres->bindParam('foo', $row['foo'], PDO::PARAM_INT);
$tres->bindParam('bar', $row['bar'], PDO::PARAM_INT);
foreach($fooData as $foo){
$db->beginTransaction();
$res->execute();
foreach($res as $row){
$tres->execute();
}
$db->commit();
}
但这导致我收到此错误消息:PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'foo' cannot be null
我尝试绑定的方式有问题吗?我可以不这样做,因为$row
是一个数组吗?