嗨,我想从Excel导入数据并存储在数据库中。以下代码可以正常工作,但是它也将列名作为记录导入。例如,如果Excel工作表包含2列,则第1列是“名称”,第2列是“电子邮件”,并且如果我选择浏览并单击“导入”,则它包含两个记录,它将向表中添加三个记录,包括其列名。我只想添加记录。


if(isset($_POST["submit"]))
{
    $file = $_FILES['file']['tmp_name'];
    $handle = fopen($file, "r");
    $c = 0;
    while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    {
        $name = $filesop[0];
        $email = $filesop[1];

        $sql = mysql_query("INSERT INTO excel(name, email) VALUES ('$name','$email')");
        $c = $c + 1;
    }

        if($sql){
            echo "You database has imported successfully. You have inserted ". $c ." recoreds";
        }else{
            echo "Sorry! There is some problem.";
        }

}

最佳答案

while循环的第一个循环包含这些列名。您已经拥有一个循环计数器,因此可以简单地跳过它

while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    {
        $c = $c + 1;
        if ($c == 1)
              continue;
        $name = $filesop[0];
        $email = $filesop[1];

        $sql = mysql_query("INSERT INTO excel(name, email) VALUES ('$name','$email')");
    }

09-11 18:33
查看更多