我无法从代码点火器中的数据库获取最后一个插入 ID



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

我创建了 2 列,1 列

仅用于自动增量,另外 1 列用于自定义 ID PTGS-1。 并且每次我都必须插入一个数据,具有自定义 id 的列总是返回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。

谢谢!

在数据库中插入记录后,输入用于获取上次插入 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;
}
我认为

问题出在您的insert_id()函数上。您需要的是拨打custom_id的最新号码,然后递增它。所以,首先调用最新的号码,我把它存储在名为insert_id的函数中:

public function insert_id()
{       
    //here is query for called max id, because u have 4 character before the number so use right instead max. 
    $sql= sprintf("SELECT MAX(RIGHT(custom_id,1)) AS key FROM your_tables_name"); 
    $qry= $this->db->query($sql);
    $row= $qry->row();
    //here is checking if the record is null
    $record= $row->key;
    if ($record== null) {
        $record = 0;
    }
    $record+= 1;
    return $record
}

最新更新