Import csv data to database according to header

here are my scripts.

if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['filename']['tmp_name'])) { echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "<br></h1>"; echo "<h2>Displaying contents:</h2>"; readfile($_FILES['filename']['tmp_name']); echo "<br>"; echo $headers; } $handle = fopen($_FILES['filename']['tmp_name'], "r"); $header = fgetcsv($handle); while(! feof($handle)){ while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT into CSVtest($header[0],$header[1],$header[2],$header[3],$header[4]) values ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')"; mysql_query($import) or die(mysql_error()); } } fclose($handle); echo "Done"; } 

This is how I insert the data into the database according to the header, even if it is not ordered in the same way as the column of the table. If csv has only "cell, firstname, lastname" (and my table has only these 3 columns), then it still works ... but if there is "cell, address, company, first name, last name", it will show me an unknown error column.

Actually, I want to have a function that even in csv columns does not exist, but in the table it cannot find the correct column and insert into the table. Can someone give me tips on how to modify my script? I know there are a lot of mistakes ... I am really embarrassed to show my low standard script ...

Thanks in advance.

+4
source share
1 answer

You want to use mysql_fetch_field to get the current columns, and then scroll through each of your headers to make sure it exists in the table when building the query.

http://php.net/manual/en/function.mysql-fetch-field.php

+3
source

All Articles