In this code today I am trying to update data in bulk. User uploads a CSV file, the system checks if the file type is correct, then fetches the data and updates the data accordingly with the help of a WHILE loop. Have a look at the code below.
if(isset($_POST['upload'])) {
if($_FILES['theFile']['name']) {
$filename = explode(".", $_FILES['theFile']['name']);
if(end($filename) == "csv") {
$handle = fopen($_FILES['theFile']['tmp_name'], "r");
while($file_data = fgetcsv($handle)) {
$id = $DBcon->real_escape_string($file_data[0]);
$newdate = $DBcon->real_escape_string($file_data[1]);
$newdate = strtotime($newdate);
$newdate = date('Y-m-d', $newdate);
$query = "UPDATE IGNORE products SET expirydate='".$newdate."' WHERE id='".$vc."'";
if ($DBcon->query($query)) {
$serror = "Customer Updatation Successful";
} else {
$error = "Something Went Wrong - Contact Support";
}
}
fclose($handle);
$serror = "Successfully Fetched Details";
} else {
$error = "Please select a CSV file";
}
} else {
$error = "Please select a CSV file";
}
}
The thing is everything works fine until we follow the rules. Let's have a look into the CSV file that works just fine.
123,11-06-2019
124,11-06-2019
125,11-06-2019
126,11-06-2019
127,11-06-2019
But when the CSV output does not includes a " , " between the columns it throws unwanted error. Here's the CSV file example
123 11-06-2019
124 11-06-2019
125 11-06-2019
126 11-06-2019
127 11-06-2019
Getting this error:
Okay
Notice
: Undefined offset: 1 in
D:\server\filepath\htdocs\filename.php
on line
21
Screenshot: http://prntscr.com/o4r9vi
The line 21 defines the next column in this case.
$newdate = $DBcon->real_escape_string($file_data[1]);
What can be done in this case to avoid/fix the error? I was thinking to throw an error when the file content does not meets certain requirements, such as when the file does not contains certain number of commas defining all the required/expected columns. But how can I do that exactly? I am pretty new to this part of PHP.
Thank you for your time.