【问题标题】:how to get last insert id after insert query in codeigniter active record如何在codeigniter活动记录中插入查询后获取最后一个插入ID
【发布时间】:2013-05-02 15:57:54
【问题描述】:

我有一个插入查询(活动记录样式),用于将表单字段插入 MySQL 表。我想获取插入操作的最后一个自动递增的 id 作为查询的返回值,但我遇到了一些问题。

控制器内部:

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);
}

内部模型:

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

由于模型中 add_post 的返回,我一无所获

【问题讨论】:

  • 对于那些想知道的人,db->insert_id()db->trans_complete() 之后返回false。确保在完成交易之前收到您的insert_id()
  • 请任何人将其标记为重复。

标签: mysql codeigniter


【解决方案1】:

试试这个

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

   return  $insert_id;
}

如果有多个插入,您可以使用

$this->db->trans_start();
$this->db->trans_complete();

【讨论】:

  • 不必要地使用事务。 @Crowlix 的回答更简洁。
  • @Abraham 并发插入呢?
  • @ShekharJoshi afaik insert_id() 函数返回您正在使用的 db 对象执行的最后一次插入的 id。这应该处理并发插入,不是吗?如果我错了,请纠正我。
  • codeigniter 如何知道特定对象添加了哪些行?
  • @ShekharJoshi 这与对象无关,CI 的 insert_id() 根据 MySQL 的 last_insert_id() 返回最后插入的 id,它在每个连接的基础上保留最后插入的 id。因此,最后插入的 id 不需要事务。
【解决方案2】:

这里不需要事务,这就足够了:

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

【讨论】:

  • 并发插入怎么样?
  • @mander 我相信 insert_id() 返回由调用它的 db 对象执行的最后一次插入的 id。即使存在并发插入,这是否意味着它总是返回与该特定 db 对象所做的插入相对应的 id?
【解决方案3】:
$id = $this->db->insert_id();

【讨论】:

    【解决方案4】:

    来自documentation

    $this->db->insert_id()

    执行数据库插入时的插入ID号。

    因此,您可以使用以下内容:

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

    【讨论】:

    • 请不要只提供链接,而是尝试在这里总结解决方案
    【解决方案5】:

    使用mysqli PHP驱动,提交后无法获取insert_id。

    真正的解决方案是这样的:

    function add_post($post_data){
      $this->db->trans_begin();
      $this->db->insert('posts',$post_data);
    
      $item_id = $this->db->insert_id();
    
      if( $this->db->trans_status() === FALSE )
      {
        $this->db->trans_rollback();
        return( 0 );
      }
      else
      {
        $this->db->trans_commit();
        return( $item_id );
      }
    }
    

    代码结构来源:https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually

    【讨论】:

      【解决方案6】:

      值得一提的是,其他答案与 Codeigniter 版本 3 相关。版本 4(找到 https://codeigniter.com/user_guide/database/helpers.html)中的答案是使用 $this->db->insertID()

      【讨论】:

        【解决方案7】:

        因为您已经通过数据插入启动了事务,所以, 首先检查交易是否完成。一旦启动事务,就应该根据事务的状态来提交或回滚;

        function add_post($post_data){
          $this->db->trans_begin() 
          $this->db->insert('posts',$post_data);
          $this->db->trans_complete();
          if ($this->db->trans_status() === FALSE){
            $this->db->trans_rollback();
            return 0;
          }else{
            $this->db->trans_commit();
            return $this->db->insert_id();
          }
        }``
        

        在上面,我们已经提交了成功交易的数据,即使你得到了时间戳

        【讨论】:

          【解决方案8】:

          只是为了完成这个话题: 如果您使用主键和自动递增设置表,则可以省略手动递增 id 的过程。

          看看这个例子

          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 . ';');
          

          现在你可以插入行了

          $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']
                  ]);
          

          【讨论】:

            【解决方案9】:
            **Inside Model**
            function add_info($data){
               $this->db->insert('tbl_user_info',$data);
               $last_id = $this->db->insert_id();
               return  $last_id;
            }
            
            **Inside Controller**
            public function save_user_record() {
              $insertId =  $this->welcome_model->save_user_info($data);
              echo $insertId->id;
            }
            

            【讨论】:

              【解决方案10】:

              你必须使用$lastId = $this->db->insert_id();

              【讨论】:

              • 你可以使用上面的好友获取最后一个插入ID
              • 重复答案
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2018-11-06
              • 1970-01-01
              • 2016-11-26
              • 1970-01-01
              相关资源
              最近更新 更多