here is 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 the way how I insert data into database according to header even it’s not arranged same as the table column.
If the csv has only “cell,firstname,lastname,,” (and my table has only these 3 columns as well) then it still working…but if there are “cell,address,company,firstname,lastname” then it will show me unknown column error.
Actually I wish to have a function that even there are many columns in csv that not exist in the table it still can just pick the right column and insert into table.
Can anyone give me hints on how to change my script?I know there are many errors…it’s really embarrassed to show my low standard script…
Thanks in advance.
You would want to use mysql_fetch_field to get current columns, and then loop through each of your headers to ensure it exists in the table while building the query.
http://php.net/manual/en/function.mysql-fetch-field.php