首页 文章

使用codeigniter和innodb引擎mysql一次插入两个表

提问于
浏览
0

你好我有两个表一个是 users &其他是 parent

父的mysql查询是

CREATE TABLE  `parent` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL DEFAULT '0',
  `name` longtext NOT NULL,
  `dob` int(10) unsigned NOT NULL DEFAULT '0',
  `sex` longtext NOT NULL,
  `address` longtext NOT NULL,
  `contact` longtext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;

用户的mysql查询是

CREATE TABLE  `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` longtext NOT NULL,
  `username` longtext NOT NULL,
  `password` longtext NOT NULL,
  `type` longtext NOT NULL,
  `status` int(10) unsigned NOT NULL DEFAULT '0',
  `online` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

我有一个包含所有上述细节的表格 . 现在我想将它们插入各自的表中 . 我也在使用CSRF保护

What I have tried

我的控制器代码

public function create()
{
$udata=array(
        'email'=>$this->input->post('email'),
        'password'=>md5($this->input->post('password')),
        'type'=>'parent',
        'online'=>'0',
        'status'=>'1'
        );
        $pdata=array(
        'name'=>$this->input->post('name'),
        'dob'=>strtotime($this->input->post('dob')),
        'gender'=>$this->input->post('gender'),
        'address'=>$this->input->post('address'),
        'contact'=>$this->input->post('contact')
        );
        $pid= $this->user_model->insert($udata,$pdata);  
}

我的模型数据

function insert($userdata,$typedata) 
    {
    $this->db->insert('users', $userdata);
    $typedata['user_id'] = $this->db->insert_id();
    $this->db->insert('parent', $typedata);
    return $this->db->insert_id(); 
    }

上面的代码只将值插入第一个表,即用户,而其他表,即parent为空 .

请注意: parent table 的user_id字段是 primary key (auto increment)users table

2 回答

  • 0

    通过使用错误记录解决问题感谢@joerg

  • 1

    最好在模型类中使用单独的函数进行插入,以避免错误

    function insertUser($userdata,$typedata) 
    {
    $this->db->insert('users', $userdata);
    return $this->db->insert_id();
    }
    
    function insertParent($typedata) 
    {
    $this->db->insert('parent', $typedata);
    return $this->db->insert_id(); 
    }
    

相关问题