My tex/csv file has 3 columns first_name
, last_name
and address
but my database table has two columns first_name
and last_name
. 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.
Some one advise me using php mysql_fetch_field
. I am trying mysql_fetch_field
and I can collect my database table columns name but I can't insert data according to table header.
set_time_limit(0);
include "connection.php"; //Connect to Database
if (isset($_POST['submit'])) {
// Gel table current column name
$query = "select * from month";
$result=mysql_query($query) or die (mysql_error());
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
$a=$meta->name;
$i++;
}
//Upload File
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$header = fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into month($header[0],$header[1]) values('$data[0]','$data[1]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
echo "Import done";
}