0

目前,我可以从名为“data.csv”的 CSV 文件中获取数据,该文件是我手动上传到 Web 服务器的。然后我可以将数据上传到数据库,这一切都很好。

我需要能够做的是:

  1. 只需将文件上传到网络服务器的根目录即可
  2. 例如,无论 CSV 文件标题的顺序如何,即使一个用户上传的 CSV 文件的列顺序是这样的(名称 | 电子邮件 | 地址),但另一用户上传的 CSV 文件的顺序是列是这样的(电子邮件|地址|名称)。所以基本上我需要将适当的数据上传到正确的数据库字段,其中 CSV 标题的名称与表中的字段名称匹配?

下面的代码:

上传.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);

?>

请问我是否没有完全正确地解释这一点。

提前致谢。

4

1 回答 1

2

The Following should be a complete solution for you.

In your 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>

In 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);

?>
于 2013-07-09T19:31:04.667 回答