我正在尝试将CSV数据发送到我的mysql数据库,但我想跳过数据的第一行,因为它包含标题,我在这里经历了一些帖子,但他们没有任何想法我怎么能在我的以下代码?????
//if ($_FILES['csv']['size'] > 0) {
if (!empty($_FILES['csv']['size']) && $_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
$num = count($data);
do {
if ($data[0]) {
mysql_query("INSERT INTO mbet_football (TIME, TEAMS, HOME, DRAW, AWAY) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: mbetf.php?success=1'); die;
}
?>
答案 0 :(得分:0)
您可以使用布尔标志跳过第一行。
//loop through the csv file and insert into database
$skipFlag = true;
while($data = fgetcsv($handle,1000,",","'")){
if($skipFlag){
$skipFlag = false;
continue;
}
if ($data[0]) {
mysql_query("INSERT INTO mbet_football (TIME, TEAMS, HOME, DRAW, AWAY) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."'
)
");
}
}
旁注:不使用mysql_*
函数,从PHP 5.5开始不推荐使用它们,在PHP 7.0中完全删除它们。请改用mysqli
或pdo
。 And this is why you shouldn't use mysql_*
functions。
答案 1 :(得分:0)
我稍微改变了你的代码,但它应该有效:
<?php
//if ($_FILES['csv']['size'] > 0) {
if (!empty($_FILES['csv']['size']) && $_FILES['csv']['size'] > 0) {
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$row = 0;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row++;
if($row == 1) continue;
if ($data[0]) {
mysql_query("INSERT INTO mbet_football (TIME, TEAMS, HOME, DRAW, AWAY) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."',
'".addslashes($data[3])."',
'".addslashes($data[4])."'
)
");
}
}
fclose($handle);
}
//redirect
header('Location: mbetf.php?success=1'); die;
}
?>
答案 2 :(得分:0)
为什么不在循环之前获得第一行?
$headers = fgetcsv($handle, 1000, ",", "'");
//loop through the csv file and insert into database
while($data = fgetcsv($handle, 1000, ",", "'")) {
//code
}