我TEX/CSV文件有3列first_name
,last_name
和address
但我的數據庫表有兩列first_name
和last_name
。我希望有一個函數,即使在表中不存在的csv
中有很多列,它仍然可以選擇右列並插入到表中。 有人建議我使用php mysql_fetch_field
。我正在嘗試mysql_fetch_field
,我可以收集我的數據庫表的列名稱,但我無法根據表頭插入數據。導入TXT/CSV數據導入數據庫
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";
}
不要使用'mysql_ *',因爲它將被棄用,請切換到'PDO'或'mysqli_ *'。另外[這裏是](http://stackoverflow.com/questions/10478861/importing-multiple-csv-files-to-mysql-tables)一個使用PDO的LOAD LOCAL INFILE的例子,它可能是有用的 –