I am trying to populate a mysql database with an excel file using phpspreadsheet library. I am doing it in the following way but I get just the first row. How can I do it for all the rows
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($target_file);
$worksheet = $spreadsheet->getActiveSheet();
$rows = [];
$outer = 1;
foreach ($worksheet->getRowIterator() AS $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
$cells = [];
foreach ($cellIterator as $cell) {
$cells[] = $cell->getValue();
}
$rows[] = $cells;
while($outer > 1){
$data = [
'testTaker' => $cells[1],
'correctAnswers' => $cells[2],
'incorrectAnswers' => $cells[3],
];
if($this->testModel->addTest($data)){
die('it worked');
} else {
die('Something went wrong');
}
}
$outer++;
}
This is how I am importing a XLSX spreadsheet with phpSpreadSheet into a MySQL database using PDO (modified to fit your criteria).
// read excel spreadsheet
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($reader) {
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($target_file);
$sheetData = $spreadsheet->getActiveSheet()->toArray();
foreach($sheetData as $row) {
// get columns
$testTaker = isset($row[0]) ? $row[0] : "";
$correctAnswers = isset($row[1]) ? $row[1] : "";
$incorrectAnswers = isset($row[2]) ? $row[2] : "";
// insert item
$query = "INSERT INTO item(testTaker, correctAnswers, incorrectAnswers) ";
$query .= "values(?, ?, ?)";
$prep = $dbh->prepare($query);
$prep->execute(array($testTaker, $correctAnswers, $incorrectAnswers));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With