반응형
codeigniter 활성 레코드에서 삽입 쿼리 후 마지막 삽입 ID를 얻는 방법
양식 필드를 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의 반환으로 아무것도 얻지 못합니다.
이 시도
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();
여기서는 거래가 필요하지 않습니다.
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
$id = $this->db->insert_id();
로부터 문서 :
$ this-> db-> insert_id ()
데이터베이스 삽입을 수행 할 때 삽입 ID 번호입니다.
따라서 다음과 같은 것을 사용할 수 있습니다.
$lastid = $this->db->insert_id();
데이터 삽입에 대해 트랜잭션을 시작 했으므로 트랜잭션이 처음 완료되었는지 확인합니다. 일단 트랜잭션을 시작하면 트랜잭션 상태에 따라 커밋되거나 롤백되어야합니다.
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();
}
}``
위에서 우리는 타임 스탬프를 얻더라도 성공적인 트랜잭션에 대한 데이터를 커밋했습니다.
이 주제를 완료하려면 다음을 수행하십시오. 기본 키 및 자동 증가로 테이블을 설정 한 경우 수동으로 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']
]);
**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;
}
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
당신은 사용해야합니다 $lastId = $this->db->insert_id();
반응형
'IT' 카테고리의 다른 글
JUnit 5 : 예외를 선언하는 방법은 무엇입니까? (0) | 2020.06.12 |
---|---|
Div 높이 100 % 및 컨텐츠에 맞게 확장 (0) | 2020.06.12 |
HTML 형식으로 PUT 메소드 사용 (0) | 2020.06.12 |
팬더 플롯에 x 및 y 레이블 추가 (0) | 2020.06.12 |
Docker : 상위 디렉토리에서 파일 추가 (0) | 2020.06.12 |