how to get last insert id after insert query in codeigniter active record

后端 未结 9 956
庸人自扰
庸人自扰 2020-11-28 01:59

I have an insert query (active record style) used to insert the form fields into a MySQL table. I want to get the last auto-incremented id for the insert operation as the re

9条回答
  •  渐次进展
    2020-11-28 02:21

    Just to complete this topic: If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.

    Check out this example

    if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
        $CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
      `serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
      `name` varchar(64) NOT NULL,
      `hash` varchar(32) NOT NULL,
      `url` varchar(120) NOT NULL,
      `datecreated` datetime NOT NULL,
      `active` tinyint(1) NOT NULL DEFAULT '1'
    ) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');
    

    Now you can insert rows

    $this->db->insert(db_prefix(). 'my_table_name', [
                'name'         => $data['name'],
                'hash'            => app_generate_hash(),
                'url'     => $data['url'],
                'datecreated'     => date('Y-m-d H:i:s'),
                'active'          => $data['active']
            ]);
    

提交回复
热议问题