Home > Blockchain >  PHP Spreadsheet populate db with all column's rows
PHP Spreadsheet populate db with all column's rows

Time:07-22

Hello i have this portion of code:

    $request->validate([
        'uploaded_file' => 'required|file|mimes:xls,xlsx'
    ]);

    $excel_file = $request->file('uploaded_file');
    $file = IOFactory::load($excel_file->getRealPath());

    $worksheet = $file->getActiveSheet();
    $highestRow = $worksheet->getHighestRow();

    $data_detail = [];

    for ($row = 9; $row < $highestRow; $row  ) {

        $data_detail['codice_articolo'] = $worksheet->getCell("A$row")->getValue();
        $data_detail['quantita'] = $worksheet->getCell("B$row")->getValue();
        $data_detail['prezzo'] = $worksheet->getCell("C$row")->getValue();

    }

Excel

enter image description here

DB:

enter image description here

I'm struggling to populate the db with rows as they are in the excel file but it's only recording first row

CodePudding user response:

The issue is here: $data_detail['codice_articolo'] = ...etc: every time you run the for loop this just overwrites the same value in the data_detail array. It seems you intended to append to this array instead.

Use this:

for ($row = 9; $row < $highestRow; $row  ) { 
  $newEntry = array();         
  $newEntry['codice_articolo'] = $worksheet->getCell("A$row")->getValue();         
  $newEntry['quantita'] = $worksheet->getCell("B$row")->getValue();         
  $newEntry['prezzo'] = $worksheet->getCell("C$row")->getValue(); 
  $data_detail[] = $newEntry;     
}

This will create a new associative array and add it to $data_detail. $data_detail then becomes a list of entries, rather than only containing a single entry.

Then later on you can loop through $data_detail and include it in your dataset for updating the database, e.g.:

foreach($data_detail as $i => $row_detail) { 
  $new_orders_details->codice_articolo = $row_detail['codice_articolo']; 
  $new_orders_details->quantita = $row_detail['quantita']; 
  $new_orders_details->prezzo = $row_detail['prezzo']; 
}
  • Related