目前,我能够从名为“data.csv”的CSV文件中获取数据,我手动上传到Web服务器。然后我可以将数据上传到数据库,这一切都正常。
我需要做的是:
以下代码:
upload.php的
<?php
include('config.php');
$file = "data.csv";
$separator = ",";
$length = 0;
$fields = array('title', 'firstName', 'secondName', 'emailAddress', 'houseNumber', 'mobileNumber', 'address1', 'address2', 'address3', 'address4', 'postcode');
$handle = fopen($file, "r");
$header = array_flip(fgetcsv($handle, $length, $separator));
$values = array();
$i = 1;
while(($csvData = fgetcsv($handle, $length, $separator)) !== false){
$values = array();
echo $i." - You have inserted another row of data into the database.<br>";
foreach ($fields as $field){
$values[] = $csvData[$header[$field]];
}
mysql_query("INSERT INTO csv (" . implode(',', array_keys($header)) . ") VALUES ('" . implode("','", $values) . "')");
$i++;
}
fclose($handle);
?>
请问我是否还没有完全解释这个问题。
提前致谢。
答案 0 :(得分:2)
以下应该是一个完整的解决方案。
在你的HTML中
<form enctype="multipart/form-data" action="sompepage.php" method="POST">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<!-- Name of input element determines name in $_FILES array -->
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
在PHP(somepage.php)
<?php
include('config.php');
$file = $_FILES['userfile']['tmp_name'];
$separator = ",";
$length = 0;
$fields = array('title', 'firstName', 'secondName', 'emailAddress', 'houseNumber', 'mobileNumber', 'address1', 'address2', 'address3', 'address4', 'postcode');
$handle = fopen($file, "r");
$header = array_flip(fgetcsv($handle, $length, $separator));
$values = array();
$i = 1;
while(($csvData = fgetcsv($handle, $length, $separator)) !== false){
$values = array();
echo $i." - You have inserted another row of data into the database.<br>";
foreach ($fields as $field){
$values[] = $csvData[$header[$field]];
}
$values = array_map("mysql_real_escape_string", $values);
mysql_query("INSERT INTO csv (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values) . "')");
$i++;
}
fclose($handle);
?>