【问题标题】:Build a PHP Mysql Importer from CSV file with headers从带有标题的 CSV 文件构建 PHP Mysql 导入器
【发布时间】:2020-04-03 22:02:18
【问题描述】:

我正在寻找构建一个 php 脚本来从引用标头的 csv 文件中导入数据。

这是我的脚本。供参考。我已经有一个 mysql 连接,就在带有标题和值的查询生成器之后。

问:谁能帮我建立一个有效的查询,因为这个不起作用。

if(isset($_POST['importSubmit'])){

    // Allowed mime types
    $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');

    // Validate whether selected file is a CSV file
    if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){

        // If the file is uploaded
        if(is_uploaded_file($_FILES['file']['tmp_name'])){

            // Open uploaded CSV file with read-only mode
            $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

            $dbTable = '_test_members';

            // Skip the first line
            //fgetcsv($csvFile);

            // Get first Row as Column Names
            $frow = fgetcsv($csvFile);

            $sqlHeaders = '(';
            $sqlHeaders .= $frow;
            $sqlHeaders .= ')';

            // Parse data from CSV file line by line
            while(($line = fgetcsv($csvFile)) !== FALSE){

                $sqlValues = ' (';
                $sqlValues .= $line;
                $sqlValues .= ') ';

                $db->query("INSERT INTO ".$dbTable." ".$sqlHeaders." VALUES ".$sqlValues."");
            }


            // Close opened CSV file
            fclose($csvFile);

            $qstring = '?status=success';
        }else{
            $qstring = '?status=error';
        }
    }else{
        $qstring = '?status=invalid_file';
    }
}

任何帮助将不胜感激。

脚本基于以下教程:https://www.codexworld.com/import-csv-file-data-into-mysql-database-php/

罗伯

【问题讨论】:

  • 不确定您的问题是什么,您是否遇到了错误,或者您只是想要一些关于您所做工作的反馈?
  • 刚刚意识到我引用的是数组而不是 CSV 行。哎呀。
  • 我遇到了错误,我觉得这是因为我使用数组而不是带有逗号分隔符的 csv 行构建了查询字符串。
  • 在这种情况下,我会在完整文件上使用 explode() 两次。主要是因为我没有意识到 fgetcsv 是一个函数,但其​​次您仍然需要查看您尝试插入的列数,因此不会引发意外错误。 PHP 的 count() 在数组上。第一个爆炸将分隔新行“PHP_EOL”,第二个是行分隔符,通常是逗号或 |在 csv 中(Idk 为什么我在这里看到 | 作为分隔符,但我有)。您应该考虑在 PHP 中使用 PDO 驱动程序进行验证。

标签: php mysql csv import


【解决方案1】:

几点说明:

请注意,上面的代码可能会被黑客入侵。请参阅owasp 指南以避免这种情况。

还有在 php 中使用 double quotes 的时间和地点。

最后,以相反的方式组合大 if 块会更简洁,这样您就不会向右滚动以到达代码的“内容”。即。

// Validate whether selected file is a CSV file
if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
                  .............
} else {
    $qstring = '?status=error';
}

应该重构为:

if(empty($_FILES['file']['name']) && in_array($_FILES['file']['type'], $csvMimes)){
    return '?status=error';
}

我明白这不是在函数的上下文中,但它可能值得重构。

祝你好运, 泰勒

【讨论】:

    猜你喜欢
    • 2014-11-23
    • 1970-01-01
    • 2017-10-15
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    相关资源
    最近更新 更多