从带有标头的CSV文件构建PHP Mysql Importer



我希望构建一个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/

几点注意事项:

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

在 php 中使用双引号也有时间和地点。

最后,以相反的方式编写大的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';
}

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

祝你好运, 泰勒

最新更新