我有CSV文件要上传它以将其上传到MySQL。
我的CSV文件的结构第一行包括名称,日期和时间等推荐信息。
从第二行开始就有信息。
我想将第一行插入名为“file_information”的表中 以及名为“main”的表格中的所有行
我的CSV如下
20151251652,1,BR-1-2
1,1-20151251652,0543434232,1234123,CL-1-3,DR-1-4,DA-12,MO-12,YR-2015,HR-12,MT-12,PA-1,LN-2,1,BR-1-2
2,1-20151251652,0543434232,1234123,CL-1-3,DR-1-4,DA-12,MO-12,YR-2015,HR-1,MT-34,PA-2,LN-2,1,BR-1-2
3,1-20151251652,0543434232,1234123,CL-1-3,DR-1-4,DA-12,MO-12,YR-2015,HR-12,MT-55,PA-2,LN-2,1,BR-1-2
4,1-20151251652,0543434232,1234123,CL-1-3,DR-1-4,DA-12,MO-12,YR-2015,HR-11,MT-20,PA-1,LN-2,1,BR-1-2
PHP
<?php
//connect to the database
$connect = mysql_connect("localhost","","");
mysql_select_db("",$connect); //select the table
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO main (control, docname, mobno, fno, cl, dr, da, mo, yr, hr, mt, pa, ln, ho, br) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."',
'".addslashes($data[5])."',
'".addslashes($data[6])."',
'".addslashes($data[7])."',
'".addslashes($data[8])."',
'".addslashes($data[9])."',
'".addslashes($data[10])."',
'".addslashes($data[11])."',
'".addslashes($data[12])."',
'".addslashes($data[13])."',
'".addslashes($data[14])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
答案 0 :(得分:0)
看一下这个例子:
<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($row == 1) {
echo "First Line :".print_r($data,1);
} else {
echo "Other Lines :".print_r($data,1);
}
$row++;
}
fclose($handle);
}
?>