如何解决php与mysql:导入.csv分隔空间
如何将此文件导入到mysql中,行之间有空格? 通过phpmyadmin可以,但是我需要通过网站来实现。
<?php
// Check if file was uploaded & there were no errors
if ($_FILES && $_FILES['csv-file']['error'] == 0) {
$extension = pathinfo($_FILES['csv-file']['name'],PATHINFO_EXTENSION);
// Check if extension is csv then proceed to import
if($extension == 'csv'){
// Open file for reading
$file = fopen($_FILES['csv-file']['tmp_name'],'r');
// Loop through all rows of file and insert them to database table
while (!feof($file)) {
// Get current row as recordset
$row = fgetcsv($file);
if (!empty($row)) {
$data = [];
$data['numbers'] = htmlentities($row[0]);
$data['tids'] = htmlentities($row[1]);
$data['date'] = htmlentities($row[2]);
$data['time'] = htmlentities($row[3]);
$data['zero'] = htmlentities($row[4]);
$data['terminal_sn'] = htmlentities($row[5]);
$data['space'] = htmlentities($row[6]);
$records[] = $data;
mysqli_query($dbcon,"INSERT INTO employees (".implode(",",array_keys($data)).") VALUES ('".implode("','",array_values($data))."')");
}
}
}else{?>
这是我的.csv文件,其中包含数据:
10222157120501 T0040922 07/09/2020 18:13:56 0 315-525-348 1
10223157120502 T0040923 07/09/2020 18:15:24 0 318-027-497 1
10224157120503 T0040924 07/09/2020 18:15:36 0 316-176-614 1
10225157120504 T0040925 07/09/2020 18:16:25 0 317-377-077 1
解决方法
// prepare the insert query once outside the loop
$sql = 'INSERT INTO employees (`numbers`,`tids`,`date`,`time`,`zero`,`terminal_sn`,`space`)
VALUES(?,?,?)';
$stmt = $dbcon->prepare($sql);
if (($handle = fopen($_FILES['csv-file']['name'],"r")) !== FALSE) {
while (($data = fgetcsv($handle,1000," ")) !== FALSE) {
// space delimiter ^
// bind the columns to the query parameters
$stmt->bind_param('sssssss',$row[0],$row[1],$row[2],$row[3],$row[4],$row[5],row[6]);
// execute the query with parameters replaced with data
$stmt->execute();
}
fclose($handle);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。