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

Php 如何上传csv文件并更新mysql数据库?,php,mysql,file-upload,csv,Php,Mysql,File Upload,Csv,我想使用csv文件来更新mysql scv表。如何编码?我没有做这项工作的经验 <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> <

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

<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?

?>
请选择要上载的scv文件


这有几个部分:

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

<form enctype="multipart/form-data"  action="index.php" method="post">
保存文件后,可以打开并导入它。这不是一件小事,但这里有一些初级代码:

// 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);
}
您的上载文件:

<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>
非常基本,很少进行检查/验证。
print\r($data)
包含一行csv,您现在可以将其插入数据库中

但是,我建议使用PDO或MySQLi来完成这项任务,因为PHP的mysql函数将来会被弃用。

可能会重复。它们不再得到维护,并且已经开始使用。看到了吗?相反,学习,并使用or-将帮助您决定哪一个。如果您选择PDO。
<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>
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);
    }
}