我的 tex/csv 文件有 3 列first_name
, 但我的数据库表有两列last_name
和. 我希望有一个功能,即使表中不存在很多列,它仍然可以选择正确的列并插入到表中。有人建议我使用 php 。我正在尝试,我可以收集我的数据库表列名称,但我无法根据表头插入数据。 address
first_name
last_name
csv
mysql_fetch_field
mysql_fetch_field
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";
}