首页 > 解决方案 > 我无法从codeigniter中的数据库中获取最后一个插入ID

问题描述

我想在 CodeIgniter 中创建一个 id,例如PTGS-11 来自具有自动增量的列以及PTGS我创建的函数。

我创建了 2 列,1 列仅用于自动增量,1 列用于自定义 id PTGS-1。并且每次我要插入数据,具有自定义 id 的列总是 return PTGS-0,它不会得到最后一个插入 id

这是我在模型中自定义 id 的函数

public function custIdPetugas() {

    $prefix = "PTGS" . "-";
    $lastid = $this->db->insert_id();

    $customid = $prefix.$lastid;

    return $customid;

}

和模型中的这个函数来处理用户输入

public function simpan() {

    $custom_id = $this->custIdPetugas();
    $post = $this->input->post();

    $data = array(
        'custom_id' => $custom_id,
        'nama_petugas' => $post['nama'],
        'username' => $post['uname'],
        'password' => password_hash($post['pword'], PASSWORD_DEFAULT),
        'tgl_lahir' => $post['tgllahir'],
        'alamat' => $post['alamat'],
        'no_telpon' => $post['notelpon']
    );

    $this->db->insert($this->tbl, $data);

}

和控制器

public function tambahPetugas() {

    $petugas = $this->PetugasModel;
    $validation = $this->form_validation;
    $validation->set_rules($petugas->rules());

    if($validation->run()) {

        $petugas->simpan();
        $this->session->set_flashdata('berhasil', 'Data berhasil ditambah!');

    }

    $this->load->view('petugas/petugas-tambah');

}

只是那个自定义ID的问题,我可以干净地将数据从表单插入到数据库,但自定义ID总是返回0。

谢谢!

标签: phpcodeignitercodeigniter-3

解决方案


在数据库中插入记录后,放置获取最后插入 ID 的代码。

$this->db->insert($this->tbl, $data);
$custom_id = $this->custIdPetugas();

但是如果你想在插入记录之前得到使用这个。假设您的最后一个插入 ID 是 99,它会给您 100 作为回报

SELECT AUTO_INCREMENT
  FROM  INFORMATION_SCHEMA.TABLES
  WHERE TABLE_SCHEMA = 'database_name'
  AND   TABLE_NAME   = 'table_name';

在插入记录之前获取最后一个插入 ID 的另一种方法。

$last_id = SELECT MAX(id) FROM table;

下一条记录按值 1 递增

模型

public function custIdPetugas() {

    $prefix = "PTGS" . "-";
    //Suppose last ID is 23 

    $lastid = $this->db->query('SELECT MAX(id) as max_id FROM table')->row();

    //$lastid = 23; Increment it by one for next unique value
    $customid = $prefix.$lastid->max_id;

    return $customid;

}

推荐阅读