php - 我无法从codeigniter中的数据库中获取最后一个插入ID
问题描述
我想在 CodeIgniter 中创建一个 id,例如PTGS-1
1 来自具有自动增量的列以及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。
谢谢!
解决方案
在数据库中插入记录后,放置获取最后插入 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;
}
推荐阅读
- python-3.x - 如何在python中加入带有序列开始到结束的破折号文件
- scanf - 如何使用scanf在单词旁边获得一个int?
- python - 替换一组python文件中的字符串
- python - ValueError:您正在尝试合并 int64 和对象列 Pands Dataframe
- clojure - Clojure:覆盖库中的一个函数
- visual-c++ - 我在询问用户每天通过的汽车并显示通过的最少卡车数量
- api - 在 Jira 中搜索以 xxx 开头的问题
- xgboost - 将训练数据拟合到 xgboost 时出现分段错误
- python - 如何更新 Piplock 文件?
- c++ - 用零初始化 std::chrono::time_point 变量