I want to upload a CSV file into my SQL database but I am getting an Undefined offset error. (Offset: 1-20). I followed the following tutorial in combination with W3schools but I don't know how to solve the error. I hope you guys can point me in the right direction. Thanks in advance.
<?php
// Load the database configuration file
include_once 'dbConfig.php';
if(isset($_POST['importSubmit'])){
// Allowed mime types
$csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
// Validate whether selected file is a CSV file
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
// If the file is uploaded
if(is_uploaded_file($_FILES['file']['tmp_name'])){
// Open uploaded CSV file with read-only mode
$csvFile = fopen($_FILES['file']['tmp_name'], 'r');
// Skip the first line
fgetcsv($csvFile);
// Parse data from CSV file line by line
while(($line = fgetcsv($csvFile)) !== FALSE){
// Get row data
$postcode = $line[0];
$week1 = $line[1];
$week2 = $line[2];
$week3 = $line[3];
$week4 = $line[4];
$week5 = $line[5];
$week6 = $line[6];
$week7 = $line[7];
$week8 = $line[8];
$week9 = $line[19];
$week10 = $line[10];
$week11 = $line[11];
$week12 = $line[12];
$week13 = $line[13];
$week14 = $line[14];
$week15 = $line[15];
$week16 = $line[16];
$week17 = $line[17];
$week18 = $line[18];
$week19 = $line[19];
$week20 = $line[20];
$db->query("INSERT INTO nlbelevering
(Postcode, Week1, Week2, Week3, Week4, Week5, Week6,
Week7, Week8, Week9, Week10, Week11, Week12, Week13,
Week14, Week15, Week16, Week17, Week18, Week19,
Week20)
VALUES ('".$postcode."', '".$week1."', '".$week2."',
'".$week3."', '".$week4."', '".$week5."',
'".$week6."', '".$week7."', '".$week8."',
'".$week9."', '".$week10."', '".$week11."',
'".$week12."', '".$week13."', '".$week14."',
'".$week15."', '".$week16."', '".$week17."',
'".$week18."', '".$week19."', '".$week20."'");
}
}
// Close opened CSV file
fclose($csvFile);
$qstring = '?status=succ';
}else{
$qstring = '?status=err';
}
}else{
$qstring = '?status=invalid_file';
}
// Redirect to the listing page
header("Location: index.php".$qstring);
The error message:
EDIT: After using the solution of RiggsFolly I can import the CSV to SQL. But it only imports the first column.



MYSQLI_orPDOAPI's instead of concatenated values$linehas the right number of elements before processing.fgetcsv()