首页 文章

使用CodeIgniter将数组数据插入到两个表中

提问于
浏览
2

我有一个注册表,并将使用注册功能将数据插入到两个不同的表中 . 这是表结构:

user

  • user_id(int)

  • user_email(varchar(64))

  • user_name(varchar(64))

  • user_pass(varchar(64))

profiles

  • prof_id(int)

  • user_id(int)

  • first_name(varchar(64))

  • last_name(varchar(64))

  • ......(其他领域)

我把变量放到两个不同的数组( $data1 & $data2 )这里是我的控制器:

function add_account() {
    $this->load->model('m_signup');
    // get form variable
    $first_name = $this->input->post('first_name');
    $last_name = $this->input->post('last_name');
    $user_email = $this->input->post('user_email');
    $user_name = $this->input->post('user_name');
    $user_pass = $this->input->post('user_pass');


    $data1 = array($user_name, $user_email, $user_pass);
    $data2 = array($first_name, $last_name);

    $this->m_signup->add_account($data1, $data2);

    redirect('login');
}

而模型是这样的:

function add_account($data1, $data2) {
    $this->db->trans_start();

    $sql1 = "INSERT INTO users(user_name, user_email, user_pass) 
            VALUES (?, ?, ?)";

    $this->db->query($sql1, $data1); 
    $id_user = $this->db->insert_id(); 

    $sql2 = "INSERT INTO profiles(user_id, first_name, last_name) 
            VALUES ($id_user, ?, ?)"; 
    $this->db->query($sql2, $data2);

    return $this->db->insert_id(); 

    $this->db->trans_complete(); 

}

当我提交注册时,其工作在表 users 中,但表 profiles 仍然是空的 . 请帮我纠正上面的 add_account function .

1 回答

  • 0

    交换线:无法访问线 $this->db->trans_complete(); .

    您在提交事务之前返回id .

    $this->db->trans_complete(); 
    
     return $this->db->insert_id();
    

相关问题