获取主键将其作为外键放在其他表中

时间:2012-07-11 11:59:35

标签: php mysql

我有这段代码,我想要做的是将主键最后插入到用户表中,然后将其放入库表的外键中。我不知道怎么用$ request或者在这做什么呢?

public function register($request = array()) {
    $data = array(
        'user_name' => $request['username'],
        'password' => $request['password'],
        'email' => ($request['email']) 
    );
    $data1 = array(
        'user_id' => '5',// this is where I have to put the primary key from last table
        'library_name' => $request['lib_name']
    );

    $this->model->insert('user', $data);
    $this->model->insert('library', $data1);
    $this->redirect('uploadSongs.php');
}

4 个答案:

答案 0 :(得分:1)

使用mysql_insert_id()

  

- 返回先前INSERT或UPDATE语句为AUTO_INCREMENT列生成的值。

答案 1 :(得分:0)

你可以这样做

public function register($request = array()) {
    $data = array(
        'user_name' => $request['username'],
        'password' => $request['password'],
        'email' => ($request['email']) 
    );

    $this->model->insert('user', $data);
   $user_id = $this->model->select('user', $data); //select user_id from db 
   $data1 = array(
        'user_id' => $user_id ,
        'library_name' => $request['lib_name']
    );



    $this->model->insert('library', $data1);
    $this->redirect('uploadSongs.php');
}

答案 2 :(得分:0)

你可以这样做

public function register($request = array()) {
$data = array(
    'user_name' => $request['username'],
    'password' => $request['password'],
    'email' => ($request['email']) 
);
$data1 = array(
    'library_name' => $request['lib_name']
);

$this->model->insert('user', $data);
$user_id = mysql_insert_id();
$data1['userid'] = $user_id;
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');

} 如果您正在使用任何框架。然后他们有帮助函数来获取最后一个插入ID,你应该使用它们

答案 3 :(得分:0)

谢谢大家,我需要做的只是改变逻辑,我使用它是愚蠢的,并没有看到在哪里放置插入查询所以它的工作现在所有我不得不做的只是改变插入查询的位置为给定

public function register($request = array()) {
$data = array(
    'user_name' => $request['username'],
    'password' => $request['password'],
    'email' => ($request['email']) 
);

$this->model->insert('user', $data);
$data1 = array(
    'user_id' => mysql_insert_id(),// now it works as insert has been done above .... 
    'library_name' => $request['lib_name']
);
$this->model->insert('library', $data1);
$this->redirect('uploadSongs.php');