1

I'm currently trying to optimize a script, that basically selects tons of data from one table, and then inserts tons of data into another table. Previously I had the code like this:

$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();
}

Now I found this great answer on stackoverflow: https://stackoverflow.com/a/19107074/2015253 and want to try to move the parameter bindings to outside of the loop, too. This is my attempt:

$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();
}

But this leads me to this error message: PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'foo' cannot be null

Is something wrong with the way I try to bind? Can I not do that because $row is an array?

Community
  • 1
  • 1
user2015253
  • 1,263
  • 4
  • 14
  • 25

0 Answers0