-1

Not sure how to format the title. pardon me.
I am using PhpSpreadsheet to INSERT the Excel column into MySql database.

What i have

enter image description here

What i tried

...

$activeSheet = $spreadsheet->getActiveSheet();
$sheetData = $activeSheet->toArray();

foreach($sheetData as $row) {
    $col1 = $row[0];

    $sql = "INSERT INTO rowascol (n1) VALUES ($col1)";
    $query = mysqli_query($con, $sql);
}

...

What i got

+----+----+----+----+----+----+
| id | n1 | n2 | n3 | n4 | n5 |
+----+----+----+----+----+----+
|  1 |  4 |    |    |    |    |
|  2 |  6 |    |    |    |    |
|  3 | 45 |    |    |    |    |
|  4 |  5 |    |    |    |    |
|  5 |  7 |    |    |    |    |
+----+----+----+----+----+----+

What i want

+----+----+----+----+----+----+
| id | n1 | n2 | n3 | n4 | n5 |
+----+----+----+----+----+----+
|  1 |  4 |  6 | 45 |  5 |  7 |
|  2 |  9 |  3 |  5 |  8 | 12 |
+----+----+----+----+----+----+
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dexter
  • 7,911
  • 4
  • 41
  • 40

1 Answers1

2

This code snippet below may help:

...

$highestColumn= ord($activeSheet->getHighestColumn())- ord('A') + 1;

for ($col = 0; $col < $highestColumn; $col++) {
    $col1 = array();
    foreach($sheetData as $row) {
        array_push($col1, $row[$col]);
    }
    $col1 = implode(',', $col1);

    $col1 = $col + 1 . ',' . $col1;  // add id
    $sql = "INSERT INTO rowascol VALUES ($col1)";
    // echo $sql;
    $query = mysqli_query($con, $sql);
}

...
jasonz
  • 1,315
  • 1
  • 17
  • 31