Im looking to build a php script to import data from a csv file that references the headers.
Here is my script. FYI. i already have a mysql connection, just after the query builder with the headers and values.
Q: Can anyone help me with building a working query, as this one does not work.
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');
$dbTable = '_test_members';
// Skip the first line
//fgetcsv($csvFile);
// Get first Row as Column Names
$frow = fgetcsv($csvFile);
$sqlHeaders = '(';
$sqlHeaders .= $frow;
$sqlHeaders .= ')';
// Parse data from CSV file line by line
while(($line = fgetcsv($csvFile)) !== FALSE){
$sqlValues = ' (';
$sqlValues .= $line;
$sqlValues .= ') ';
$db->query("INSERT INTO ".$dbTable." ".$sqlHeaders." VALUES ".$sqlValues."");
}
// Close opened CSV file
fclose($csvFile);
$qstring = '?status=success';
}else{
$qstring = '?status=error';
}
}else{
$qstring = '?status=invalid_file';
}
}
Any help would be greatly appreciated.
Script has been based on the following tutorial: https://www.codexworld.com/import-csv-file-data-into-mysql-database-php/
Rob