简体   繁体   中英

Cannot get last inserted id to autofill form field

I'm am unable to get last inserted id with codeigniter and grocery crud and then pass them to autofill a field. How can I do that? I'm trying to solve with a function returning id and passing by the hidden field.

Post edited. Everything in the right order I'm working.

Database (Involved tables: citas, entregas)

Database

Scheme (Cita = date inserted):

Image from the process

Model function

 public function get_id(){                 

  //$this->db->query('SELECT MAX(cita) FROM citas;');
    $this->db->insert_id();
    $query = $this->db->get();

    echo $query;

    return $query->result();        

}

Controller(full controller function)

 public function entregas_lista($idCarga) {

        $crud = new grocery_CRUD();



        if ($this->Entregas_Model->get_rows($idCarga)) {
            $crud->unset_add();
        }


        $datos = array(
            'title' => "Solicitudes", 
            'username' => "Administrador"
        );

        $this->load->view('commons/header', $datos);



        $crud->set_language("spanish");
        $crud->set_theme('flexigrid');

        $crud->set_table('entregas');


        $crud->display_as('idCitas', 'Cita');
        $crud->display_as('idAcciones', 'Acción');
        $crud->display_as('idEstadoSolicitud', 'Estado Solicitud')
                ->display_as('horaCita', 'Hora Cita')
                ->display_as('numeroEntrega', 'Nº Entrega')
                ->display_as('Origen', 'Orígen')
                ->display_as('cargaPrevista', 'Carga Prevista')
                ->display_as('entregaPrevista', 'Entrega Prevista');



        $crud->where('entregas.idCitas =', $idCarga);

        $crud->display_as('idCarga', 'Nº Entrega');


        $crud->set_relation('idEstadoSolicitud', 'estadosolicitudes', 'nombreEstado');




        $query = $this->Entregas_Model->get_id();

        $crud->field_type('idCitas', 'hidden', $query);

        $output = $crud->render();

        $this->_example_output($output);


        $this->load->view('commons/footer');
    }

In order to use insert_id() in Codeigniter, you must Insert a new row in your DB. Otherwise you have to select the MAX(id) from your table

Example of insert_id() :

$this->db->insert('test_table', $test_data);
return $this->db->insert_id();

Example of MAX(id) :

$qry = $this->db->select('MAX(id)')
                ->from('test_table')
                ->get();
        if ($qry->num_rows() > 0)
            return $qry->row_array();
        return FALSE;

and you grab it in your Controller.

first $this->db->insert($table,$data);

after $insert_id= $this->db->insert_id();

echo $insert_id;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM