【问题标题】:Catch error in insert_batch codeigniter在 insert_batch codeigniter 中捕获错误
【发布时间】:2016-09-03 17:20:00
【问题描述】:

我混合使用 ajax 和 codeigniter 来进行多次插入。

代码如下所示:

JS

function save(path){
    $.ajax({
        url: "<?php echo site_url('members/megumi/container_list/import_from_csv'); ?>",
        type: 'post',
        data: {path: path},
        success: function (response) {
            reload_table();
            $('#modal_form').modal('hide'); // show bootstrap modal

        }
    });
    return false;
}

PHP 代码点火器

 public function import_from_csv(){
    $csv = $this->input->post('path');

    $tryOne = array();

    if (file_exists($csv)) {
        $file = fopen($csv, 'r'); // r flag is for readonly mode

        while (( $line = fgetcsv($file) ) !== false) { // if line exists
            $tryOne[] = $line; // add to array

        }
        fclose($file);
    }

    $tryOne = array_map(function($insert){
        return array(
            'CONSIGNEE' => $insert[1],
            'CONTAINER' => $insert[2],
            'SEAL' => $insert[3],
            'THICK' => $insert[4],
            'WIDTH' => $insert[5],
            'SIZE' => $insert[6],
            'COAT' => $insert[7],
            'SPEC' => $insert[8],
            'COIL_NO' => $insert[9],
            'QTY' => $insert[10],
            'PALET' => $insert[11],
            'NET' => $insert[12],
            'GROSS' => $insert[13],
            'CONTRACT_NO' => $insert[14],
            'TGL_TRANSFER' => $insert[15],
            'LENGTH' => $insert[16],
            'GRADE' => $insert[17],
            'NO_URUT' => $insert[18]

        );
    }, $tryOne);

    $insert = $this->container->insert_batch_data($tryOne);
    echo json_encode($insert);
}

假设多次插入失败,因为我的 MySQL 表中有 UNIQUE 列。我在萤火虫上遇到了这个错误:

发生数据库错误

错误号:1062

密钥“COIL_NO”的重复条目“02NKTL216036109-2-1/8”

如何向普通用户显示这样的错误:“抱歉,出现问题,请检查您上传的 CSV”。

有可能吗?

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    您所要做的就是修改您使用insert_batch()insert_batch_data() 方法,如下所示

    $this->db->db_debug = false;
    // .....
     $insert = $this->db->insert_batch('table_name', $tryOne);
        if($insert > 0){
           $test = TRUE;
        }else{
            $test = FALSE;
        }
    return $test;
    

    现在在控制器import_from_csv()

    echo json_encode($insert);
    

    这会将布尔值发送到您的 ajax。或者您可以根据您的要求返回任何数据。所以技巧是使用$this-&gt;db-&gt;db_debug = false;隐藏数据库错误

    您可以使用config.php 隐藏所有数据库错误,其中db_debug 选项可设置为FALSE

    【讨论】:

    • 在 $this->db->db_debug = false 上很好。谢谢!
    【解决方案2】:

    你需要在你的PHP端使用一个TRY/CATCH,这样如果数据不正确你可以抛出一个错误,更多信息在这里:http://php.net/manual/en/language.exceptions.php

    基本上你需要尝试执行上传,如果数据不正确,它会向用户抛出一个“nice”错误...

    【讨论】:

    • insert_batch ci 中的错误不适用于 TRY/CATCH
    猜你喜欢
    • 2014-02-07
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多