这是我导入csv数据时使用的代码,但是如何从第2行开始导入数据呢?由于第一行是列名称(ID,Student Name,Subject Code,Subject Name,Unit,Grade)
。
if (isset($_POST["submitgrade"])){
if ($_FILES["file"]["name"]){
$filename = explode('.',$_FILES["file"]["name"]);
if ($filename[1] == 'csv')
$handle = fopen($_FILES["file"]["tmp_name"], "r");
while ($data = fgetcsv($handle))
{
$item1 = mysqli_real_escape_string($con, $data[0]);
$item2 = mysqli_real_escape_string($con, $data[1]);
$item3 = mysqli_real_escape_string($con, $data[2]);
$item4 = mysqli_real_escape_string($con, $data[3]);
$item5 = mysqli_real_escape_string($con, $data[4]);
$item6 = mysqli_real_escape_string($con, $data[5]);
$grade = "INSERT into subj (username,name,code,title,unit,grade) values ('$item1','$item2','$item3','$item4','$item5','$item6')";
mysqli_query($con,$grade);
}
fclose($handle);
echo 'Upload Grade Success';
}}
答案 0 :(得分:1)
在while
循环开始迭代CSV文件之前,写一次语句$data = fgetcsv($handle)
。然后按原样启动循环。循环将从CSV文件的第2行开始。
答案 1 :(得分:0)
您只需添加计数器和变量即可轻松访问。在这种情况下,$ startAtLine将从第1行开始。
<?php
if (isset($_POST["submitgrade"])){
if ($_FILES["file"]["name"]){
//These two lines are added
$startAtLine = 0;
$counter = 0;
$filename = explode('.',$_FILES["file"]["name"]);
if ($filename[1] == 'csv')
$handle = fopen($_FILES["file"]["tmp_name"], "r");
while ($data = fgetcsv($handle))
{
if(++$counter<$startAtLine)
continue;
$item1 = mysqli_real_escape_string($con, $data[0]);
$item2 = mysqli_real_escape_string($con, $data[1]);
$item3 = mysqli_real_escape_string($con, $data[2]);
$item4 = mysqli_real_escape_string($con, $data[3]);
$item5 = mysqli_real_escape_string($con, $data[4]);
$item6 = mysqli_real_escape_string($con, $data[5]);
$grade = "INSERT into subj (username,name,code,title,unit,grade) values ('$item1','$item2','$item3','$item4','$item5','$item6')";
mysqli_query($con,$grade);
}
fclose($handle);
echo 'Upload Grade Success';
}}
?>