Rez*_*eri 152 mysql codeigniter
我有一个插入查询(活动记录样式)用于将表单字段插入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);
}
Run Code Online (Sandbox Code Playgroud)
内部模型:
function add_post($post_data){
$this->db->trans_start();
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
return $this->db->insert_id();
}
Run Code Online (Sandbox Code Playgroud)
我没有得到任何东西作为模型中add_post的返回
Sud*_*udz 255
试试这个
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Run Code Online (Sandbox Code Playgroud)
如果有多个插入,您可以使用
$this->db->trans_start();
$this->db->trans_complete();
Run Code Online (Sandbox Code Playgroud)
Cro*_*lix 62
这里不需要交易,这应该足够了:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
Run Code Online (Sandbox Code Playgroud)
Md.*_*Mia 10
从文档:
$这个 - > DB-> INSERT_ID()
执行数据库插入时的插入ID号.
因此,你可以使用这样的东西:
$lastid = $this->db->insert_id();
Run Code Online (Sandbox Code Playgroud)
使用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 );
}
}
Run Code Online (Sandbox Code Playgroud)
代码结构来源:https ://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually
归档时间: |
|
查看次数: |
382818 次 |
最近记录: |