Php 在插入之前验证CSV数据有效性以及CSV文件名,如果其间存在错误/缺少数据,则不要插入到数据库中

Php 在插入之前验证CSV数据有效性以及CSV文件名,如果其间存在错误/缺少数据,则不要插入到数据库中,php,mysql,validation,csv,Php,Mysql,Validation,Csv,我需要有关在插入之前验证CSV数据以及CSV文件名的帮助,如果其间存在错误/缺少数据,请不要插入到数据库并打印错误消息 try { if(isset($_POST['importSubmit'])){ //validate whether uploaded file is a csv file $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values',

我需要有关在插入之前验证CSV数据以及CSV文件名的帮助,如果其间存在错误/缺少数据,请不要插入到数据库并打印错误消息

try {
    if(isset($_POST['importSubmit'])){
        //validate whether uploaded file is a csv file
        $csvMimes = array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
        $surveydate = $_POST['surveydate'];
        $userID = $_SESSION['userID'];

        if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
            if(is_uploaded_file($_FILES['file']['tmp_name'])){
                //open uploaded csv file with read only mode
                $csvFile = fopen($_FILES['file']['tmp_name'], 'r');

                //skip first line
                fgetcsv($csvFile);

                //parse data from csv file line by line
                while(($line = fgetcsv($csvFile)) !== FALSE) {
                    //check whether member already exists in database with same email
                    //insert member data into database
                    $db->query("INSERT INTO communitysurvey (surveyNum,stationID,age,gender,educationalattainment,question,response,userID,surveydate) VALUES('".$line[0]."', '".$line[1]."','".$line[2]."', '".$line[3]."', '".$line[4]."','".$line[5]."','".$line[6]."','{$userID}','{$surveydate}')");
                }

                //problem on userID session won't get inserted
                //close opened csv file
                fclose($csvFile);      
            }
        }
    }

    //redirect to the listing page
    header("Location: inputcommunity.php".$qstring);
} catch (Exception $e) {
    alert ($e->getMessage());
}

要从CSV中获取数据,您可以对
while
循环中读入的每一行使用分隔符(可能是“、”或“、”表示CSV)并进行分解。这将返回该行中每个值的数组。您可以检查此数组的长度是否缺少值,并将类型/值与预期值进行比较以检查“正确性”。

在代码中的何处需要帮助?您好!我需要帮助编码数据验证,以确保我的CSV文件中的所有数据字段都已填充,如果存在en-empty字段或不正确的ID,则会在其中放置一个字符串。它将显示错误消息,不会插入数据库。