Is it bad to put a MySQL query in a PHP loop?

前端 未结 5 2072
庸人自扰
庸人自扰 2021-02-05 23:56

I often have large arrays, or large amounts of dynamic data in PHP that I need to run MySQL queries to handle.

Is there a better way to run many processes like INSERT or

5条回答
  •  青春惊慌失措
    2021-02-06 00:44

    I was inspired by jerebear's answer to build something like his second option for one of my current projects. Because of the shear volume of records I couldn't save and do all the data at once. So I built this to do imports. You add your data, and then call a method when each record is done. After a certain, configurable, number of records the data in memory will be saved with a mass insert like jerebear's second option.

    // CREATE TABLE example ( Id INT, Field1 INT, Field2 INT, Field3 INT);
    $import=new DataImport($dbh, 'example', 'Id, Field1, Field2, Field3');
    foreach ($whatever as $row) {
      // add data in the order of your column definition
      $import->addValue($Id);
      $import->addValue($Field1);
      $import->addValue($Field2);
      $import->addValue($Field3);
      $import->nextRow();
    }
    $import->lastRow();
    

提交回复
热议问题