通过CSV导入数据时的错误处理

时间:2018-03-05 06:51:53

标签: php import-csv

我需要在导入数据时考虑CSV文件时处理任何错误。 我需要实现的是显示成功上传的行总行数和错误(如果有)。

下面是我需要展示的线框图像

enter image description here

以下是我目前使用的代码:

include_once("db_connect.php");
if(isset($_POST['import_data'])){    
    // validate to check uploaded file is a valid csv file
    $file_mimes = 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');
    if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$file_mimes)){
        if(is_uploaded_file($_FILES['file']['tmp_name'])){   
            $csv_file = fopen($_FILES['file']['tmp_name'], 'r');           
            //fgetcsv($csv_file);            
            // get data records from csv file
            while(($emp_record = fgetcsv($csv_file)) !== FALSE){
                // Check if employee already exists with same email
              $c++;
              if($c != "1"){
                $sql_query = "SELECT emp_id, emp_name, emp_salary, emp_age FROM emp WHERE emp_email = '".$emp_record[2]."'";
                $resultset = mysqli_query($conn, $sql_query) or die("database error:". mysqli_error($conn));
                // if employee already exist then update details otherwise insert new record
                if(mysqli_num_rows($resultset)) {                     
                    $import_status = '?import_status=exists';
                } else{
                    $mysql_insert = "INSERT INTO emp (emp_name, emp_email, emp_salary, emp_age )VALUES('".$emp_record[1]."', '".$emp_record[2]."', '".$emp_record[3]."', '".$emp_record[4]."')";
                    mysqli_query($conn, $mysql_insert) or die("database error:". mysqli_error($conn));
                    $import_status = '?import_status=success';
                }
              }

            }            
            fclose($csv_file);

        } else {
            $import_status = '?import_status=error';
        }
    } else {
        $import_status = '?import_status=invalid_file';
    }
}
header("Location: upload_employee_data_open_link.php".$import_status);

1 个答案:

答案 0 :(得分:0)

SQL Ignore用于忽略任何与查询相关的错误。它将跳过错误并继续进行下一个查询。希望对别人有帮助