【问题标题】:why there is an extra record stored in mysql database?为什么mysql数据库中存储了额外的记录?
【发布时间】:2020-12-12 16:12:59
【问题描述】:

我创建了一个 csv 到 mysql 数据库导入器。 代码-

<?php 

include_once("connection.php");


if(isset($_POST["import"])){
$filename =  $_FILES["file"]["tmp_name"];

if($_FILES["file"]["size"] > 0){
    $file = fopen($filename, "r");

    while(($column = fgetcsv($file,10000, ",")) !== FALSE){
        $sqlInsert = "INSERT INTO datasets (name,email,phone) values('" . $column[0] . "', '". $column[1] . "', '" . $column[2] . "')";
        $result = mysqli_query($con,$sqlInsert);

        if(!empty($result)){
            echo "CSV data imported into database !";
        }
        else{
            echo "Error importing data into database ...";
        }
    }
    
}
}

?>

表格代码是-

<form class="form-container my-5" action="backend/api.php" method="POST" enctype="multipart/form-data">
    <div class="form-group">
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
            </div>
            <div class="custom-file">
                <input type="file" name="file" accept=".csv" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01">
                <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
            </div>
        </div>
    </div>
    <button type="submit" name="import" class="btn btn-primary">Submit</button>
</form>

但是,记录应该是这样的——

所以,我将意外数据标记为红色。我不知道为什么会这样显示?代码有错误吗?

【问题讨论】:

  • 没有多余的记录。您的代码将 csv 文件的全部内容存储在数据库中
  • csv 的第一行是标题,您需要跳过它。
  • @RolandStarke 跳过它?有没有办法让它不在数据库中显示?
  • 啊,是的,我的意思是跳过插入,因此它不在数据库中。例如,您可以在 while 循环之前添加:fgetcsv($file,10000, ","); //read first line and throw away to skip header 或在您的 while 循环中执行 if($column[1] === 'email') { continue; }
  • @Dharman 是的,我现在将更改它.. 只是快速测试一些东西。无论如何感谢您的提醒

标签: php mysql csv


【解决方案1】:

您需要跳过 CSV 文件的标题行。只是不要执行第一行的 SQL 语句。

您更正后的代码应如下所示:

<?php

include_once "connection.php";

if (isset($_POST["import"])) {
    $filename = $_FILES["file"]["tmp_name"];

    if ($_FILES["file"]["size"] > 0) {
        $file = fopen($filename, "r");
        
        $stmt = $con->prepare('INSERT INTO datasets (name,email,phone) values(?,?,?)');

        $headerRow = true;
        while (($column = fgetcsv($file, 10000, ",")) !== false) {
            if ($headerRow) {
                $headerRow = false;
                continue;
            }
            $stmt->bind_param('sss', $column[0], $column[1], $column[2]);
            $stmt->execute();
        }
        echo "CSV data imported into database !";
    }
}

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多