cómo obtener el último id de inserción después de insertar consulta en codeigniter active record


Tengo una consulta insert (estilo active record) utilizada para insertar los campos del formulario en una tabla MySQL. Quiero obtener el último id auto-incrementado para la operación de inserción como el valor devuelto de mi consulta, pero tengo algunos problemas con él.

Dentro del controlador:

function add_post(){
    $post_data = array(
        'id'            => '',
        'user_id'   =>  '11330',
        'content'   =>  $this->input->post('poster_textarea'),
        'date_time' => date("Y-m-d H:i:s"),
        'status'        =>  '1'
    );
    return $this->blog_model->add_post($post_data);
}

Y dentro del modelo:

function add_post($post_data){
    $this->db->trans_start();
    $this->db->insert('posts',$post_data);
    $this->db->trans_complete();
    return $this->db->insert_id();
}

No obtengo nada como el retorno del add_post en el modelo

Author: Mel, 2013-05-08

5 answers

Prueba esto

function add_post($post_data){
   $this->db->insert('posts', $post_data);
   $insert_id = $this->db->insert_id();

   return  $insert_id;
}

En caso de múltiples inserciones se podría utilizar

$this->db->trans_start();
$this->db->trans_complete();
 204
Author: Sudz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-25 08:35:26

Una transacción no es necesaria aquí, esto debería ser suficiente:

function add_post($post_data) {
    $this->db->insert('posts',$post_data);
    return $this->db->insert_id();
}
 58
Author: Crowlix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-17 15:32:24
$id = $this->db->insert_id();
 26
Author: Simon Carlson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-08 12:22:12

De la documentación :

This this - > db - >insert_id ()

El número de ID de inserción al realizar inserciones de base de datos.

Por lo tanto, podrías usar algo como esto:

$lastid = $this->db->insert_id();
 5
Author: Md.Jewel Mia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-21 16:33:54

Debes usar $lastId = $this->db->insert_id();

 0
Author: Pawan Kr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 05:55:35