在数据库中上传CSV文件-PHP

时间:2019-11-15 10:56:11

标签: php csv file-upload fgetcsv

这是我的代码。我收到错误消息“注意:未定义的偏移量:9”。如果我有直到$ item9都可以,但是我实际上希望有直到$ item13。

if(isset($_POST["submit"]))
{
    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($connect, $data[0]);
                $item2 = mysqli_real_escape_string($connect, $data[1]);
                $item3 = mysqli_real_escape_string($connect, $data[2]);
                $item4 = mysqli_real_escape_string($connect, $data[3]);
                $item5 = mysqli_real_escape_string($connect, $data[4]);
                $item6 = mysqli_real_escape_string($connect, $data[5]);
                $item7 = mysqli_real_escape_string($connect, $data[6]);
                $item8 = mysqli_real_escape_string($connect, $data[7]);
                $item9 = mysqli_real_escape_string($connect, $data[8]);
                $item10 = mysqli_real_escape_string($connect, $data[9]);


                $query = "INSERT into tab1(country, jan, feb,mar,apr,may,jun,jul,aug) values('$item1','$item2','$item3','$item4','$item5','$item6','$item7','$item8','$item9','$item10')";
                mysqli_query($connect, $query);
            }
            fclose($handle);

1 个答案:

答案 0 :(得分:0)

您在最后一条评论中回答了自己。所以你说的话-例如。像这样替换每个项目行:

$item1 = array_key_exists(0, $data) ? mysqli_real_escape_string($connect, $data[0]) : '0';