0

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

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

在此处输入图像描述

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

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);
4

1 回答 1

0

SQL Ignore 用于忽略任何与查询相关的错误。它将跳过错误并传递到下一个查询。希望它可以帮助某人

于 2019-09-27T07:30:11.460 回答