【问题标题】:Skip first line uploading csv into mysql using PHP跳过使用 PHP 将 csv 上传到 mysql 的第一行
【发布时间】:2019-04-07 10:04:27
【问题描述】:

我想在使用 PHP 将 CSV(标题部分)上传到 MySQL 时跳过第一行,但它总是将第一行插入 MySQL 表中,并且它也不会上传 MySQL 中的总记录。我的 CSV 中有 1000 条记录,但一次只上传 174 条记录。我正在使用以下代码将 CSV 上传到 MySQL。任何人都知道我做错了什么。

    <?php

include 'config.php';
$flag = true;
 if(isset($_POST["import"])){

        $filename=$_FILES["file"]["tmp_name"];      


         if($_FILES["file"]["size"] > 0)
         {
            $file = fopen($filename, "r");
            while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
             {

 if($flag)
  {
   $flag = false;
    continue;
     }
               $sql = "INSERT into tbl_customer(customer_name,customer_excise_code,city) 
                   values ('".$getData[0]."','".$getData[1]."','".$getData[2]."')";

                   $result = mysqli_query($conn, $sql);
                if(!isset($result))
                {
                    echo "<script type=\"text/javascript\">
                            alert(\"Invalid File:Please Upload CSV File.\");
                            window.location = \"index.php\"
                          </script>";       
                }
                else {
                      echo "<script type=\"text/javascript\">
                        alert(\"CSV File has been successfully Imported.\");
                        window.location = \"index2.php\"
                    </script>";
                }
             }

             fclose($file); 
         }
    }    


 ?>

【问题讨论】:

  • MySQL 的 LOAD DATA INFILE 语句可以快速导入 CSV 文件,并且可以从头开始

标签: php mysql sql database mysql-workbench


【解决方案1】:

您可以尝试下一个建议:

  • if($flag) {...} 之前检查文件中的空行
  • 您对isset() 的检查将始终返回true,因为mysqli_query() 返回布尔值或对象,因此您不知道语句是否正确执行。您执行INSERT 语句,在这种情况下mysqli_query() 的预期结果将是布尔值,因此只需检查$result

PHP:

<?php
$flag = true;
...

while (($getData = fgetcsv($file, 10000, ",")) !== FALSE) {
    if (is_null($getData[0])) {
        continue;
    }
    if ($flag) {
        $flag = false;
        continue;
    }
    ...

    $result = mysqli_query($conn, $sql);
    if (!$result) {
        ...
    } else {
        ...
    }   

    ...
}

...
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多