⚠ In case you've missed it, we have migrated to our new website, with a brand new forum. For more details about the migration you can read our blog post for website migration. This is an archived forum. ⚠

  •     

profile picture

Problem inserting and updating datetime with callbacks



Carloco

Carloco
  • profile picture
  • Member

Posted 18 June 2013 - 03:48 AM

Hi everybody

 

I am developing a web page, in that I put some fields and a datetime field in order to let the user to pick a datetime value and all that value are inserted or updated in the table of my mysql database. (the datatype of the field is datetime too).

 

I am using callbacks for insert and update and there is the problem, all the fields(varchars,integers) are inserted and updated very well

except by the datetime field. Without the two callbacks(insert and update) all the fields are inserted including the datetime field but I am using stored procedures so I must use the callbacks to avoid the auto insert-update of the crud.

 

If anyone knows how to fix this I would appreciate it. Thanks.


davidoster

davidoster
  • profile picture
  • Member

Posted 20 June 2013 - 14:19 PM

Hello and welcome to the forums [member=carloco].

Please post your controller's code, along with the callbacks.

Also post the structure of the table along with the stored procedures you mentioned.


Carloco

Carloco
  • profile picture
  • Member

Posted 21 June 2013 - 03:20 AM

CODE OF THE CONTROLLER

 

<?php 
if(!defined('BASEPATH'))
    exit("No se puede ejecutar directamente el script");
    
class admin_resultados extends CI_Controller {
    
    function admin_resultados() {
        parent::__construct();
        $this->load->model('mod_ConexionBD','DB');
    }
    
    function _remap($me) {
        if(!$this->session->userdata('user') && $this->session->userdata('Fecha y hora de logout')) { 
            redirect('login','refresh');
        }
        switch($me) {
            case 'show_admin_resultados': $this->show_admin_resultados(); break; 
        }
    }
    
    public function show_admin_resultados() {
        try {
             /* Creamos el objeto */
            $crud = new grocery_CRUD();
    
            /* Seleccionamos el tema */
            $crud->set_theme('datatables');
        
            /* Seleccionmos el nombre de la tabla de nuestra base de datos*/
            $crud->set_table('tbl_resultados');
        
            /* Le asignamos un nombre */
            $crud->set_subject('Resultados');
        
            /* Asignamos el idioma español */
            $crud->set_language('spanish');
        
            /* Aqui le decimos a grocery que estos campos son obligatorios */
            $crud->required_fields(
              'res_num_fecha',
              'res_equ_local',
              'res_equ_visit',
              'res_gol_local',
              'res_gol_visit',
              'res_fecha',
              'res_estadio',
              'res_estado'
            );
            
            /* Aqui le indicamos que campos deseamos mostrar en la lista */
            $crud->columns(
              //'res_id',
              'res_num_fecha',
              'res_equ_local',
              'res_gol_local',
              'res_equ_visit',
              'res_gol_visit',
              'res_estadio',
              'res_fecha',
              'res_estado'
            );
            
            // Aqui indicamos los campos que queremos mostrar al agregar un nuevo registro
            $crud->fields(
              'res_num_fecha',
              'res_equ_local',
              'res_equ_visit',
              'res_gol_local',
              'res_gol_visit',
              'res_fecha', // HERE IS THE FIELD THAT DON'T WOTKS WITH THE CALLBACKS
              'res_estadio',
              'res_estado',
              'res_incidencias'
            );
            
            // Aqui ponemos alias a los campos        
            //$crud->display_as('res_id','ID');
            $crud->display_as('res_num_fecha','Jornada');
            $crud->display_as('res_equ_local','Equipo local');
            $crud->display_as('res_equ_visit','Equipo visitante');
            $crud->display_as('res_gol_local','Goles equipo local');
            $crud->display_as('res_gol_visit','Goles equipo visitante');
            $crud->display_as('res_fecha','Fecha y hora del partido');
            $crud->display_as('res_estadio','Estadio');
            $crud->display_as('res_estado','Estado del partido');
            $crud->display_as('res_fecha_insert','Fecha de creacion');
            $crud->display_as('res_fecha_update','Ultima modificacion');
            $crud->display_as('res_incidencias','Incidencias');
            
            $crud->field_type('res_gol_local','integer');
            $crud->field_type('res_gol_visit','integer');
            $crud->field_type('res_fecha','datetime');
            
            $crud->set_relation('res_equ_local','tbl_equipos','equ_nombre');
            $crud->set_relation('res_equ_visit','tbl_equipos','equ_nombre');
            $crud->set_relation('res_estado','tbl_estados','est_estado');
            $crud->field_type('res_estadio','dropdown',$this->_loadEstadios());
            
            //$crud->callback_before_insert(array($this,'valEquipos'));
            $crud->callback_insert(array($this,'_insertResultado'));
            $crud->callback_update(array($this,'_updateResultado'));
                                                
            /* Generamos la tabla */
            $output = $crud->render();
        
            // cargamos la vista
            $this->load->view('view_admin_resultados', $output);
            
        }
        catch(Exception $e) {
            show_error('ERROR: '.$e->getMessage().' --- '.$e->getTraceAsString());
        }
        
    }
       
    function _loadEstadios() {
        $estadios = $this->db->query('SELECT equ_estadio FROM view_estadios');
        $eq = array();
        foreach($estadios->result() as $equ) {
            $eq[$equ->equ_estadio] = $equ->equ_estadio;
        }
        return $eq;  
    }
    
    function _loadEquipos() {
        $equipos = $this->db->query('SELECT * FROM view_equipos');
        $eq = array();
        foreach($equipos->result() as $equ) {
            $eq[$equ->equ_nombre] = $equ->equ_nombre;
        }
        return $eq;
    }
    
    // CALLBACK FOR INSERT(INSERT ALL FIELDS BUT NO THE FIELD 'res_fecha'')
    function _insertResultado($post) {
        if(($post['res_equ_local'] == $post['res_equ_visit'])) {
            //$this->lib_utils->mensaje('Error al insertar');
            return false;
        }
        else {
            $sp = "CALL sp_insert_resultado(?,?,?,?,?,?,?,?,?)";
            return $this->db->query($sp,array(
                                          'res_num_fecha' => $post['res_num_fecha'],
                                          'res_equ_local' => $post['res_equ_local'],
                                          'res_equ_visit' => $post['res_equ_visit'],
                                          'res_gol_local' => $post['res_gol_local'],
                                          'res_gol_visit' => $post['res_gol_visit'],
                                          'res_fecha' => $post['res_fecha'],
                                          'res_estadio' => $post['res_estadio'],
                                          'res_estado' => $post['res_estado'],
                                          'res_incidencias' => $post['res_incidencias']));
        }            
    }
    
    // CALLBACK FOR UPDATE(UPDATE ALL FIELDS BUT NO THE FIELD 'res_fecha'')
    function _updateResultado($post,$pk) {
        if(($post['res_equ_local'] == $post['res_equ_visit'])) {
            //$this->lib_utils->mensaje('Error al actualizar');
            return false;
        }
        else {
            $sp = "CALL sp_update_resultado(?,?,?,?,?,?,?,?,?,?)";
            return $this->db->query($sp,array(
                                          'res_id' => $pk,
                                          'res_num_fecha' => $post['res_num_fecha'],
                                          'res_equ_local' => $post['res_equ_local'],
                                          'res_equ_visit' => $post['res_equ_visit'],
                                          'res_gol_local' => $post['res_gol_local'],
                                          'res_gol_visit' => $post['res_gol_visit'],
                                          'res_fecha' => $post['res_fecha'],
                                          'res_estadio' => $post['res_estadio'],
                                          'res_estado' => $post['res_estado'],
                                          'res_incidencias' => $post['res_incidencias']));
        }
    }
}
 
?>
 
 
STRUCTURE OF THE TABLE AND SP
 
CREATE TABLE `tbl_resultados` (
  `res_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Clave primaria del registro',
  `res_num_fecha` varchar(15) COLLATE latin1_spanish_ci NOT NULL COMMENT 'Numero de la fecha del campeonato ej. --> "Fecha # 18"',
  `res_equ_local` varchar(11) COLLATE latin1_spanish_ci NOT NULL COMMENT 'Equipo local',
  `res_equ_visit` varchar(11) COLLATE latin1_spanish_ci NOT NULL COMMENT 'Equipo visitante',
  `res_gol_local` int(2) NOT NULL COMMENT 'Goles del equipo local',
  `res_gol_visit` int(2) NOT NULL COMMENT 'Goles del equipo visitante',
  `res_fecha` datetime NOT NULL COMMENT 'Fecha del partido',
  `res_estadio` varchar(100) COLLATE latin1_spanish_ci NOT NULL COMMENT 'Nombre del estadio',
  `res_estado` int(11) NOT NULL COMMENT 'Codigo asociado al estado del partido (En juego, Finalizado)',
  `res_incidencias` varchar(200) COLLATE latin1_spanish_ci DEFAULT NULL COMMENT 'Informacion relevante sobre el partido',
  `res_fecha_insert` datetime NOT NULL COMMENT 'Fecha y hora de creacion del registro',
  `res_fecha_update` datetime NOT NULL COMMENT 'Fecha y hora de modificacion del registro',
  PRIMARY KEY (`res_id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci;
 
/* Procedure structure for procedure `sp_insert_resultado` */
 
/*!50003 DROP PROCEDURE IF EXISTS  `sp_insert_resultado` */;
 
DELIMITER $$
 
/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insert_resultado`(in num_fecha varchar(15),in elocal varchar(11),in evisit varchar(11),
   in glocal integer,in gvisit integer, in fecha datetime, in estadio varchar(100),   in estado integer, in incidencias varchar(200))
BEGIN
INSERT INTO tbl_resultados
            (`res_num_fecha`,
             `res_equ_local`,
             `res_equ_visit`,
             `res_gol_local`,
             `res_gol_visit`,
             `res_fecha`,
             `res_estadio`,
             `res_estado`,
             `res_incidencias`)
VALUES(num_fecha,elocal,evisit,glocal,gvisit,fecha,estadio,estado,incidencias);
    END */$$
DELIMITER ;
 
/* Procedure structure for procedure `sp_update_resultado` */
 
/*!50003 DROP PROCEDURE IF EXISTS  `sp_update_resultado` */;
 
DELIMITER $$
 
/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_update_resultado`(in id integer,IN num_fecha VARCHAR(15),IN elocal VARCHAR(11),IN evisit VARCHAR(11),  IN glocal INTEGER,IN gvisit INTEGER, IN fecha datetime, IN estadio VARCHAR(100), IN estado INTEGER, IN incidencias VARCHAR(200))
BEGIN
UPDATE tbl_resultados
SET 
 `res_num_fecha` = num_fecha,
 `res_equ_local` = elocal,
 `res_equ_visit` = evisit,
 `res_gol_local` = glocal,
 `res_gol_visit` = gvisit,
 `res_fecha` = fecha,
 `res_estadio` = estadio,
 `res_estado` = estado,
 `res_incidencias` = res_incidencias
WHERE `res_id` = id;
    END */$$
DELIMITER ;

 


davidoster

davidoster
  • profile picture
  • Member

Posted 21 June 2013 - 23:39 PM

Try this first of all,

on your function show_admin_resultados()

use the set_primary_key function.

And let us know if this resolves your problem.


Carloco

Carloco
  • profile picture
  • Member

Posted 22 June 2013 - 00:50 AM

Nop, it didn't work. I don't really know what to do now jeje.


davidoster

davidoster
  • profile picture
  • Member

Posted 22 June 2013 - 01:05 AM

Can you please explain something,

 

these two 

 `res_fecha_insert` datetime NOT NULL COMMENT 'Fecha y hora de creacion del registro',
  `res_fecha_update` datetime NOT NULL COMMENT 'Fecha y hora de modificacion del registro',

are NOT NULL but you don't include them at the $crud->fields or at the stored procedure. How do you manage to insert a new record?


Carloco

Carloco
  • profile picture
  • Member

Posted 22 June 2013 - 12:20 PM

Ah, those two fields are datetime too but I use triggers to insert or update. Those fields represents the datetime when the user created the register and the datetime when the user modified the register.


goFrendiAsgard

goFrendiAsgard
  • profile picture
  • Member

Posted 22 June 2013 - 16:49 PM

Hi, [member="Carloco"].
Sorry, I don't really get your point. You have tbl_resultados and once you insert something to it, you call a procedure to insert something to it again.

What do you intend to do?

 

I'm not sure if I can help, but I think the problem laid on php & mysql different date format.

MySQL use 'yyyy-mm-dd'. So how about change your code a bit:

function _updateResultado($post,$pk) {
        if(($post['res_equ_local'] == $post['res_equ_visit'])) {
            //$this->lib_utils->mensaje('Error al actualizar');
            return false;
        }
        else {
            $sp = "CALL sp_update_resultado(?,?,?,?,?,?,?,?,?,?)";
            return $this->db->query($sp,array(
                                          'res_id' => $pk,
                                          'res_num_fecha' => $post['res_num_fecha'],
                                          'res_equ_local' => $post['res_equ_local'],
                                          'res_equ_visit' => $post['res_equ_visit'],
                                          'res_gol_local' => $post['res_gol_local'],
                                          'res_gol_visit' => $post['res_gol_visit'],
                                          'res_fecha' => date('Y-m-d H:i:s', strtotime(str_replace('-', '/', ;$post['res_fecha']))),
                                          'res_estadio' => $post['res_estadio'],
                                          'res_estado' => $post['res_estado'],
                                          'res_incidencias' => $post['res_incidencias']));
        }
    }

Carloco

Carloco
  • profile picture
  • Member

Posted 22 June 2013 - 21:12 PM

I am going to try it, thanks a lot


Carloco

Carloco
  • profile picture
  • Member

Posted 22 June 2013 - 21:41 PM

THANK GOD jeje it works!! thank you sou much  goFrendiAsgard and davidoster for your time and help. The code is perfect but I had to change it a bit:

 

str_replace('/', '-', ;$post['res_fecha']) --> the '/' char must be replaced by the '-' because that is the separator of the datetime in MySQL.

 

Thank you very much and saludos desde Guayaquil, Ecuador


wgomez

wgomez
  • profile picture
  • Member

Posted 13 February 2017 - 17:17 PM

Es posible traer los datos a la grilla mediante un procedimiento almacenado ?. En el sistema en que estoy trabajando, en muchas partes los datos que debo traer a la grilla, son procesados de esta forma.