如何上传csv文件并更新mysql数据库?

时间:2012-11-28 19:59:53

标签: php mysql file-upload csv

我想使用csv文件来更新mysql csv表。如何编码?我没有这方面的工作经验。

<p>please select a scv file to upload</p>
<form action="index.php" method="post">
    <input type="file" name="scv"  />
    <input type="submit" value="submit" />
</form>
<?php 
    mysql_connect('localhost','root','admin');
    mysql_select_db('linjuming');
    // how to upload a scv file and insert or update the "csv" table?

?>

enter image description here

2 个答案:

答案 0 :(得分:1)

这有几个部分:

首先,您的表单必须设置enctype,如下所示:

<form enctype="multipart/form-data"  action="index.php" method="post">

否则,它将不接受文件上传。

完成后,您可以使用$_FILES变量访问该文件。文件上传后,您可以像这样访问它:

if (isset($_FILES["scv"])) {
    $file = $_FILES["scv"];
    $file_name = $file["name"];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);
    if ($ext!="CSV" && $ext!="TXT") {
        die('The file must be csv or txt format.');
    }
    $saveto_path_and_name = '/path/to/file.csv'; // Where you want to save the file
    move_uploaded_file($file["tmp_name"], $saveto_path_and_name);
}

保存文件后,即可打开并导入。这不是一件容易的事,但这里有一些引物代码:

// Open the file for reading
$handle = @fopen($saveto_path_and_name, "r") or die(__("Unable to open uploaded file!", "inventory"));
// Grab the first row to do some checks
$row = fgets($inv_file, 4096);
// See if it's comma or tab delimited
if (stripos($inv_row, "\t")) {
    $sep = "\t";
} else {
    $sep = ",";
}

while ( ! feof($handle)) {
    $rowcount = 0;
    // Get the individual fields
    $inv_fields = explode($sep, $inv_row);
    $fields = array();
    // Iterate through the fields to do any sanitization, etc.
    foreach ($inv_fields as $field) {
        // Highly recommended to sanitize the variable $field here....
        $fields[] = $field;
        $rowcount++;
}
    // This is where you would write your query statement to insert the data
    // This is just EXAMPLE code.  Use the DB access of your choice (PDO, MySQLi)
    $sql = vsprintf('INSERT INTO `table` (`column`, `column2`, ...) VALUES (%s, %d, ...)', $fields);
    // Get the next row of data from the file
    $row = fgets($inv_file, 4096);
}

答案 1 :(得分:1)

您的上传文件:

<form action="upload_target.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

您的upload_target.php

$ ext = pathinfo($ _ FILES ['file'] ['name'],PATHINFO_EXTENSION);

if ($ext == "csv" && $_FILES["file"]["error"] == 0)
{
    $target = "upload/" . $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], $target);

    if (($handle = fopen($target, "r")) !== FALSE) 
    {
        while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) 
        {
            print_r($data);
        }

        fclose($handle);
    }
}

非常基本,只有很少的检查/验证。 print_r($data)包含您现在可以在数据库中插入的一行csv。

但是,我建议使用PDO或MySQLi来完成该任务,因为将来不推荐使用PHP的mysql函数。