I have a problem calling a Stored Procedure with codeigniter, the stored is to generate an id autonumeric this is the code, I use PHP 7.0
, MySQL
, Codeigniter 3
, jQuery 3.1
.
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE 'sp_autonumerico'(IN 'pkeyconfig' VARCHAR(25))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE pkey VARCHAR(25);
DECLARE EXIT HANDLER FOR SQLEXCEPTION ROLLBACK;
DECLARE EXIT HANDLER FOR SQLWARNING ROLLBACK;
START TRANSACTION;
SET pkey=pkeyconfig;
UPDATE autonumerico SET valor=valor+1 WHERE llave = CONVERT(pkey using utf8) collate utf8_spanish_ci;
SELECT llave, valor FROM autonumerico WHERE llave = CONVERT(pkey using utf8) collate utf8_spanish_ci;
COMMIT;
END$$
DELIMITER ;
When executing it, it updates the table autonumerico
and performs a Select on the same table. So far so good.
Now, in my model, I call the stored as follows.
public function sp_autonumerico() {
if($query = $this->db->query("CALL sp_autonumerico('id_usuario')")){
return $query->result();
} else {
return show_error('Error!');
}
}
This returns an array with the values of the autonumeric table. This part apparently also is correct.
Now I have my controller with a function to perform a insert
traditionally so I've done the following process but without the codeigniter framework.
ID
I assign the value that the stored one brings Here I leave the code of my controller.
public function insert_user() {
$this->form_validation->set_rules('txt_primer_nombre', 'Primer_Nombre', 'trim|required|max_length[99]');
$this->form_validation->set_rules('txt_apellido_paterno', 'Apellido_Paterno', 'trim|required|max_length[99]');
$this->form_validation->set_rules('txt_puesto', 'Puesto', 'trim|required|max_length[99]');
#$this->form_validation->set_rules('txt_correo', 'Correo', 'trim|required|valid_email|is_unique[usuarios.correo_electronico]|max_length[249]');
$this->form_validation->set_rules('txt_password', 'Password', 'trim|required|min_length[6]|max_length[249]');
if ($this->form_validation->run() == FALSE) {
$data["mensaje_error"] = "Error";
} else {
$config['upload_path'] = "assets/img/upload";
$config['allowed_types'] = 'jpg|png';
$config['encrypt_name'] = TRUE;
$config['max_size'] = '2048'; //2 MB
$this->load->library('upload', $config);
if ($this->upload->do_upload("file")) {
$data = $this->upload->data();
//Resize and Compress Image
$config['image_library'] = 'gd2';
$config['source_image'] = 'assets/img/upload/' . $data['file_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['quality'] = '60%';
$config['width'] = 1024;
$config['height'] = 768;
$config['new_image'] = 'assets/img/upload/' . $data['file_name'];
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$image = $data['file_name'];
}
$idCliente = $this->input->post('hid_id_usuario');
$primerNombre = $this->input->post('txt_primer_nombre');
$segundoNombre = $this->input->post('txt_segundo_nombre');
$apellidoPaterno = $this->input->post('txt_apellido_paterno');
$apellidoMaterno = $this->input->post('txt_apellido_materno');
$nombreCorto = $this->input->post('hid_nombre_corto');
$checkNombreCorto = $this->input->post('hid_nombre_checkbox');
$puesto = $this->input->post('txt_puesto');
$sueldo = $this->input->post('txt_sueldo');
$periodoSueldo = $this->input->post('hid_id_periodo_sueldo');
$permisos = $this->input->post('list_permisos');
$colorUsuario = $this->input->post('hid_color_usuario');
$correoElectronico = $this->input->post('txt_correo');
$password = $this->input->post('txt_password');
if ($idCliente == 0) {
#Aqui llamo al stored procedure
$sp['auto'] = $this->Extras->sp_autonumerico();
#Obtengo el valor de la consulta
$idAutonumerico = $sp['auto'][0]->valor;
$this->db->set('fecha_alta', 'NOW()', FALSE);
$this->db->set('fecha_edicion', 'NOW()', FALSE);
if (isset($image)) {
#deberia de enviar el valor del stored
$datosController = array("id_usuario" => (int)$idAutonumerico, "path_img" => $image, "primer_nombre" => $primerNombre, "segundo_nombre" => $segundoNombre, "apellido_paterno" => $apellidoPaterno,
"apellido_materno" => $apellidoMaterno, "nombre_corto" => $nombreCorto, "checkbox_nombre_corto" => $checkNombreCorto, "puesto" => $puesto, "sueldo" => $sueldo, "id_periodo_sueldo" => $periodoSueldo,
"id_permiso" => $permisos, "color_usuario" => $colorUsuario, "correo_electronico" => $correoElectronico,
"password" => $password);
}
$insert = $this->Extras->insert_user_model($datosController);
if ($insert) {
$data["users"] = $this->Extras->select_usuarios();
$data['insert_ok'] = '<script type="text/javascript">swal("Ok", "Registro correcto");</script>';
$this->load->view('ajax_table_user', $data);
}
#SI EL STORED LO LLAMO AQUI ME IMPRIME EL VALOR SIN PROBLEMAS
} else {
$this->db->set('fecha_edicion', 'NOW()', FALSE);
#Actualiza datos con imagen
if (isset($image)) {
$datosControllerUpdate = array("path_img" => $image, "primer_nombre" => $primerNombre, "segundo_nombre" => $segundoNombre, "apellido_paterno" => $apellidoPaterno,
"apellido_materno" => $apellidoMaterno, "nombre_corto" => $nombreCorto, "checkbox_nombre_corto" => $checkNombreCorto, "puesto" => $puesto, "sueldo" => $sueldo, "id_periodo_sueldo" => $periodoSueldo,
"id_horas_extra" => $horasExtra, "id_permiso" => $permisos, "id_funciones_proyecto" => $funcionesProyecto, "color_usuario" => $colorUsuario, "correo_electronico" => $correoElectronico,
"password" => $password);
$deleteFile = $this->Extras->get_usario($idCliente);
#Elimina la imagen del usuario
$imagenDelete = $deleteFile->path_img;
if (isset($imagenDelete)) {
$path = 'assets/img/upload/';
$get_file = $path . $imagenDelete;
if (file_exists($get_file)) {
unlink($get_file);
}
}
}
$update = $this->Extras->update_usuario($idCliente, $datosControllerUpdate);
/* @var $update type */
if ($update) {
$data["users"] = $this->Extras->select_usuarios();
$data['update_ok'] = '<script type="text/javascript">
swal({
title: "Ok",
text: "Actualización correcta"
}).then(function() {
window.location = "http://192.168.1.71/gantt/index.php/usuarios/";
});</script>';
$this->load->view('ajax_table_user', $data);
}
}
}
}
Now this controller is executing it from a JS with ajax
which is the following.
$('#btn_guardar').click(function () {
var id_cliente = parseInt($("#hid_id_usuario").val());
var file_data = $('#btn_upload_usuario').prop('files')[0];
var txt_primer_nombre = $("#txt_primer_nombre").val();
var txt_segundo_nombre = $("#txt_segundo_nombre").val();
var txt_apellido_paterno = $("#txt_apellido_paterno").val();
var txt_apellido_materno = $("#txt_apellido_materno").val();
var hid_nombre_corto = $("#hid_nombre_corto").val();
var hid_nombre_checkbox = $("#hid_nombre_checkbox").val();
var txt_puesto = $("#txt_puesto").val();
var txt_sueldo = $("#txt_sueldo").val();
var txt_peridod_sueldo = $("#hid_id_periodo_sueldo").val();
var list_permisos = $("#list_permisos").val();
var txt_color_usuario_hexa = $("#hid_color_usuario").val();
var txt_correo = $("#txt_correo").val();
var txt_password = $("#txt_password").val();
var txt_password_verify = $("#txt_password_verify").val();
var expresionEmail = /^\w+([\.\+\-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
//Aqui van todas las validaciones
var form_data = new FormData();
form_data.append('hid_id_usuario', id_cliente);
form_data.append('file', file_data);
form_data.append('txt_primer_nombre', txt_primer_nombre);
form_data.append('txt_segundo_nombre', txt_segundo_nombre);
form_data.append('txt_apellido_paterno', txt_apellido_paterno);
form_data.append('txt_apellido_materno', txt_apellido_materno);
form_data.append('hid_nombre_corto', hid_nombre_corto);
form_data.append('hid_nombre_checkbox', hid_nombre_checkbox);
form_data.append('txt_puesto', txt_puesto);
form_data.append('txt_sueldo', txt_sueldo);
form_data.append('hid_id_periodo_sueldo', txt_peridod_sueldo);
form_data.append('list_permisos', list_permisos);
form_data.append('hid_color_usuario', txt_color_usuario_hexa);
form_data.append('txt_correo', txt_correo);
form_data.append('txt_password', txt_password);
$.ajax({
type: 'POST',
url: baseurl + 'index.php/usuarios/insert_user',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
beforeSend: function (data) {
$('#table_user').html();
},
success: function (data) {
$('#table_user').html(data);
},
complete: function () {
$('#hid_id_usuario').val('0');
$('#btn_upload_usuario').val('');
$("#txt_primer_nombre").val('');
$("#txt_segundo_nombre").val('');
$("#txt_apellido_paterno").val('');
$("#txt_apellido_materno").val('');
$("#hid_nombre_corto").val('');
$("#hid_nombre_checkbox").val();
$("#txt_puesto").val('');
$("#txt_sueldo").val('');
$("#hid_id_periodo_sueldo").val('');
$("#hid_color_usuario").val('');
$("#txt_correo").val('');
$("#txt_password").val('');
$("#txt_password_verify").val('');
$("#img_user").attr("src", 'http://192.168.1.71/gantt/assets/img/photos/icon_user_2.png');
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === '|') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$("#table_user").html(msg);
}
});
});
The problem is when I run the script the error message Internal Server Error [500].
is always sent and the insert is not done. The insert script works correctly because before doing the stored insert correctly with the auto_increment
even now if I comment the stored and pass the numerical value manually the insert is done correctly.
Someone might have some idea that I'm doing wrong, I need the stored to assign the same value to another different insert to be executed later. Thanks.