I am trying to import a CSV file into MySQL using CodeIgniter 4, but I’m facing an issue. When I printed my query, I noticed some dummy text before the column names, like:
INSERT INTO tbl_user
(.ApplicationNo
) VALUES (‘123XXX’);
This is causing me to be unable to save records to the table.
Could you please help me correct this issue?
Thank you.
`<?php
$file = $this->request->getFile(“file”);
if ($file->isValid() && !$file->hasMoved()) {
$newName = $file->getRandomName();
$uploadPath = ROOTPATH . "uploads/";
if (!is_dir($uploadPath)) {
mkdir($uploadPath, 0777, true);
}
$file->move($uploadPath, $newName);
$csvFilePath = $uploadPath . $newName;
$file = fopen($csvFilePath, "r");
$data = [];
$headers = fgetcsv($file);
$headers = array_map("trim", $headers);
while (($row = fgetcsv($file)) !== false) {
// Trim whitespace from each row value
$row = array_map("trim", $row);
// Create associative array combining headers and current row
$rowData = array_combine($headers, $row);
// Add row data to the data array
$data[] = $rowData;
}
fclose($file);
$appModel->insertBatch($data);
unlink($csvFilePath);
return $adminModel->jsonResponse(true, SAVE_SUCCESS);
}
return $adminModel->jsonResponse(true, “Invalid file”);
`