I mixed ajax and codeigniter to doing multiple insert.
The code looked like this:
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);
}
Let's say multiple insert is failed because there are UNIQUE column in my MySQL table. I got this error on firebug :
A Database Error Occurred
Error Number: 1062
Duplicate entry '02NKTL216036109-2-1/8 ' for key 'COIL_NO'
How can I display just an error like this to common user: "Sorry, there is a problem, please check your uploaded CSV".
Is it possible?
All you have to do is modify your insert_batch_data()
method where you use insert_batch()
as follows
$this->db->db_debug = false;
// .....
$insert = $this->db->insert_batch('table_name', $tryOne);
if($insert > 0){
$test = TRUE;
}else{
$test = FALSE;
}
return $test;
Now in controller import_from_csv()
echo json_encode($insert);
this will send Boolean to your ajax. Or you may return any data based on your requirements. So the tricks is hide DB error using $this->db->db_debug = false;
You may hide all DB error by using config.php
where db_debug
option available to set as FALSE
You need to use a TRY/CATCH in your PHP side, this way you can throw an error if the data is incorrect, more information here: http://php.net/manual/en/language.exceptions.php
Basically you need to try to perform the upload, and if the data is incorrect it would throw a 'nice' error back to the user...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.