php - 从带有标题的 CSV 文件构建 PHP Mysql 导入器

标签 php mysql csv import

我希望构建一个 php 脚本来从引用 header 的 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/

最佳答案

一些注意事项:

请注意,您可能会被上面的代码攻击。引用owasp指南以避免这种情况。

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

最后,以相反的方式组成大的 if block 会更干净,这样您就不会向右滚动以获取代码的“核心”。即。

// 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';
}

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

祝你好运, 泰勒

关于php - 从带有标题的 CSV 文件构建 PHP Mysql 导入器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59271947/

相关文章:

Python MySQL 比较两个表

python - 如何在 Python 中将 CSV 列读取为字符串

php - Magento 类别产品重新索引错误

php - 如何在 PHP 中抽象 mysqli 准备好的语句?

php - FOSRestBundle:如何避免 POST/登录路由的自动复数化?

php - E_ALL | 有什么意义? E_STRICT 是否与 E_ALL 的值相同?

mysql - SQL按日和月选择查询顺序

mysql - SQL查询获取2个表之间的结果,第二个有3种返回数据的可能性

python - Pandas :如何解决 "error tokenizing data"?

php - 在 PHP 上解析来自 base64 的 csv 文件