我将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 Codeigniter
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列。我在firebug上遇到了这个错误:
发生数据库错误
错误号码:1062
对于'COIL_NO'键重复输入'02NKTL216036109-2-1 / 8'
如何向普通用户显示这样的错误:“抱歉,有问题,请检查上传的CSV”。
有可能吗?
答案 0 :(得分:2)
您需要做的就是修改insert_batch_data()
使用insert_batch()
的方法,如下所示
$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->db->db_debug = false;
您可以使用config.php
隐藏所有数据库错误,db_debug
选项可设置为FALSE
答案 1 :(得分:0)
您需要在PHP端使用TRY / CATCH,这样如果数据不正确就会抛出错误,更多信息请点击此处:http://php.net/manual/en/language.exceptions.php
基本上你需要尝试执行上传,如果数据不正确,它会向用户抛出一个“好”的错误......