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

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

最佳答案

您上传的文件:

<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['文件']['名称'], 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 函数将来将被弃用。

关于php - 如何上传 csv 文件并更新 mysql 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13613413/

相关文章:

php - httppost mysql 为空

php - 使用 jQuery 将多维数组转为表格

php - 通过php比较日期

php - 如何编写脚本来更改 MySQL 数据库中的整数?

grails - 如何保存上传的图片

php - 将数组与外部数组组合

java - Android向php发送数据并接收问题nullpointerException

MySQL - 从持续时间中减去时间(不是日期时间)

javascript - Isset 不适用于 ajax 调用

使用 Apache FileUpload 时出现 java.lang.NoClassDefFoundError