我无法从codeigniter中的数据库中获取最后一个插入ID

时间:2019-01-01 06:09:03

标签: php codeigniter codeigniter-3

我想在CodeIgniter中创建一个PTGS-1这样的ID,其中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。

谢谢!

2 个答案:

答案 0 :(得分:2)

在数据库中插入记录后,放置获取最后插入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;

}

答案 1 :(得分:1)

我认为问题出在您的Sub test() Dim v As Variant v = Range("C4").FormulaR1C1 Range("C7:C11").FormulaR1C1 = v v = Range("D4").FormulaR1C1 Range("D7:D11").FormulaR1C1 = v End Sub 函数中。您需要的是从insert_id()中拨打最新号码,然后递增。因此,首先调用最新号码,我将其存储在名为custom_id的函数中:

insert_id