dtcaw02086 2017-02-03 12:21
浏览 72
已采纳

MySQL在(PHP)循环内部执行INSERT。 INSERT仅在第一个循环上运行

I have a code to upload xlsx to Mysql tables and the load is done with chunks because the file is too large, so I have to INSERT every chunk. The for loop works good it has been tested with echo statements but the INSERT is only done in the first chunk. Any idea of how I can solve this? This is part of the code:

for ($startRow = 2; $startRow <= $totalRows; $startRow += $chunkSize) {
  $chunkFilter->setRows($startRow,$chunkSize);
  //Load of the data
  $objPHPExcel = $objReader->load($newFilePath);
  $objWorksheet4 = $objPHPExcel -> getSheetByName("MIFReportExport");
  //Getting data of every cell
  $highestRow4 = $objWorksheet4->getHighestRow();
  $highestColumn4 = $objWorksheet4->getHighestColumn();
  $highestColumnIndex4 = PHPExcel_Cell::columnIndexFromString($highestColumn4);
  $rows = array();
  for ($row = 2; $row <= $highestRow4; ++$row) {
     for ($col = 0; $col <= $highestColumnIndex4; ++$col) {
          $rows[$col] = $objWorksheet4->getCellByColumnAndRow($col, $row)->getCalculatedValue();
}
 $result = mysql_query("INSERT INTO fy16 (SerialNumber, BrandedModelName, GenericProductCode, Familia, ProductLineModelFile)VALUES ('".$rows[0]."', '".$rows[1]."', '".$rows[2]."', '".$rows[3]."', '".$rows[4]."', '".$rows[5]."')",$con) or die(mysql_error());

}

}

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongzhi1949 2017-02-03 13:11
    关注

    First of all, you should take a look at PDO, and prepared statements. Here is how to create a MASS insert query

    $valuesToInsert = [
        ["firstColumn" => "item1", "secondColumn" => "item1"],
        ["firstColumn" => "item2", "secondColumn" => "item2"],
        ["firstColumn" => "item3", "secondColumn" => "item3"],
    ];
    
    $valuesTab = array_map(function ($tab) { return "({$tab['firstColumn']}, {$tab['secondColumn']})"; },$valuesToInsert);
    
    
    $query = "INSERT INTO `tableName` (firstColumn, secondColumn) VALUES ". implode(',', $valuesTab);
    

    Output :

    INSERT INTO
      `tableName` (firstColumn, secondColumn)
    VALUES
      (item1, item1),(item2, item2),(item3, item3)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 根据以下文字信息,做EA模型图
  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥60 关机时蓝屏并显示KMODE_EXCEPTION_NOT_HANDLED,怎么修?
  • ¥66 如何制作支付宝扫码跳转到发红包界面