PHP导入CSV转义字符串问题

时间:2019-05-20 19:23:40

标签: php import-csv

我正在尝试使用PHP代码将csv文件导入到我的网站。 mysqli_real_escape_string可以正常工作,但是当我在数据库上检查数据时,表的下一列没有数据。

我尝试将mysqli_real_escape_string添加到所有数组($ impData) 但是,除了上面带有(')的列$ impData [10]和$ impData [14]之外,所有数据均不会添加。

        //check if input file is empty
    if(!empty($_FILES['file']['name'])){
        $filename = $_FILES['file']['tmp_name'];
        $fileinfo = pathinfo($_FILES['file']['name']);

            //check file extension
        if(strtolower($fileinfo['extension']) == 'csv'){
                //check if file contains data
            if($_FILES['file']['size'] > 0){



                $file = fopen($filename, 'r');
                $flag = true;
                $date_created = date("Y-m-d H:i:s");
                while(($impData = fgetcsv($file, '', ',')) !== FALSE){
                    $sql = "INSERT INTO asset_inventory (asset_type, asset_device, computer_name, serial_number, asset_tag, status, status_type, claim_status, claim_date, floor, workstation_number, unit, segment, assigned_user, purchase_order, invoice_number, vendor, brand, model, date_received, snow_ticket, rcs_owner, notes, date_created) VALUES ('".$impData[0]."', '".$impData[1]."', '".$impData[2]."', '".$impData[3]."', '".$impData[4]."', '".$impData[5]."', '".$impData[6]."', '".$impData[7]."', '".$impData[8]."', '".$impData[9]."', '".mysqli_real_escape_string($impData[10])."', '".$impData[11]."', '".$impData[12]."', '".$impData[13]."', '".mysqli_real_escape_string($impData[14])."', '".$impData[15]."', '".$impData[16]."', '".$impData[17]."', '".$impData[18]."', '".$impData[19]."', '".$impData[20]."', '".$impData[21]."', '".$impData[22]."', '".$date_created."')";
                    if($flag) { $flag = false; continue; }
                    $query = $conn->query($sql);

                    if($query){
                        $_SESSION['message'] = "Data imported successfully";
                    }
                    else{
                        $_SESSION['message'] = "Cannot import data. Something went wrong";
                    }
                }
                header('location: ../inventory.php');

            }
            else{
                $_SESSION['message'] = "File contains empty data";
                header('location: ../inventory.php');
            }
        }
        else{
            $_SESSION['message'] = "Please upload CSV files only";
            header('location: ../inventory.php');
        }
    }
    else{
        $_SESSION['message'] = "Unable to upload CSV: File empty";
        header('location: ../inventory.php');
    }

}

else{
    $_SESSION['message'] = "Please import a file first";
    header('location: ../inventory.php');
} 

I expected to import all the data to the database even without (') on it.

0 个答案:

没有答案