我想使用PHP将.csv文件上传到MySQL数据库。我有这段代码:
<?php
include_once 'db.php';
if(isset($_POST['submit'])){
if($_FILES['csv_data']['name']){
$arrFileName = explode('.',$_FILES['csv_data']['name']);
if($arrFileName[1] == 'csv'){
$handle = fopen($_FILES['csv_data']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$item1 = mysqli_real_escape_string($dbConnection,$data[0]);
$item2 = mysqli_real_escape_string($dbConnection,$data[1]);
$import="INSERT into tbl_csv values('','$item1','$item2')";
mysqli_query($dbConnection,$import);
}
fclose($handle);
print "Import done";
}
}
else{
echo "only Excel";
}
}
?>
<html>
<head>
<title>CSV Upload</title>
<head>
<body>
<form method='POST' enctype='multipart/form-data'>
Upload CSV: <input type='file' name='csv_data' /> <input type='submit' name='submit' value='import' />
</form>
</body>
</html>
工作正常。但我想上传没有列标题的.csv文件。例如,如果我上传文件:
id item1 item2
1 a b
2 b c
每次插入id
,item1
和item2
。
如何解决这个问题?
答案 0 :(得分:0)
将上面的内容放在while循环中非常简单:
$headers = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$item1 = mysqli_real_escape_string($dbConnection,$data[0]);
$item2 = mysqli_real_escape_string($dbConnection,$data[1]);
....