Search code examples
phpfilecsvfgetcsv

Insert csv data into mysql according to headers


I have a simple scripts to upload csv file and it works . But how if I want to handle the data with headers specified? Such as if my table have 3 columns: FirstName,LastName,Address and now my csv file is:

Address,FirstName,LastName
myadd,myfname,mylname

How to insert the data correctly into mysql according to the headers even it's not arrange same as table column name?

If I using my scripts , it will just insert myadd,myfname and mylname into FirstName,LastName and Address , even the headers will be inserted as well.

if (isset($_POST['upload'])) {

if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
    echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
    echo "<p>contents:</p>";
    readfile($_FILES['filename']['tmp_name']);
}


$handle = fopen($_FILES['filename']['tmp_name'], "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $import="INSERT into CSVtest($column1,$column2,$column3,$column4,$column5) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";

    mysql_query($import) or die(mysql_error());
}

fclose($handle);

Echo "Done";

}


Solution

  • You say you have scripts : "If I using my scripts , it will just insert myadd,myfname and mylname into FirstName,LastName and Address , even the headers will be inserted as well."

    I assume your scripts are generating the SQL to do this, namely you are saying INSERT INTO tablename VALUES(v1,v2,v3);

    instead of doing it that way, do a named insert INSERT INTO user (f1,f2,f3) VALUES('v1','v2','v3');

    in other words specify the field names in the script that generates the sql.