Codeigniter - 在第二个表中插入用户ID的两个表

时间:2015-02-28 00:33:33

标签: php mysql codeigniter

我正在尝试插入两个表格。在我的第一个表格中,我插入了基本的用户信息。在第二个表上,我需要用户ID来设置我的站点的默认文本。例如。 “这是你的第一篇文章。你可以点击进行编辑。”等

到目前为止我的代码:

//adds the basic user info to the users database
 $sql = "INSERT INTO users (first_name, last_name, username, email, password, IP, total_entry, average_entry, date_of_registration, lastactive, account_state)
    VALUES (" . $this->db->escape($first_name) . ",
             " . $this->db->escape($last_name) . ",
             " . $this->db->escape($username) . ",
             '" . $email . "',
             '" . $password . "',
             '" . $IP . "',
             '" . $total_entry . "',
             '" . $average_entry . "',
             '" . $date_of_registration . "',
             '" . $lastactive . "',
             '" . $account_state . "')";  

        //adds the basic entry to the database   
    $data = array(
        'message' => $message,
        'picture' => $picture,
        'uid' => $uid, //problem here, since the $uid is undefined
        'time' => $date_of_registration,
    );

    $this->db->insert('entries', $data);

所以我需要先保存注册用户,然后使用用户的UID更新第二个表。

codeidniter 中执行此操作的最佳方法是什么?

由于

1 个答案:

答案 0 :(得分:1)

你应该在$ data数组中使用$ this-> db-> insert_id()作为uid值,这样就可以了:

//将基本用户信息添加到用户数据库

$ sql =" INSERT INTO用户(first_name,last_name,用户名,电子邮件,密码,IP,total_entry,average_entry,date_of_registration,lastactive,account_state)     VALUES("。$ this-> db-> escape($ first_name)。",              " 。 $ this-> db-> escape($ last_name)。 &#34 ;,              " 。 $ this-> db-> escape($ username)。 &#34 ;,              '" 。 $ email。 "&#39 ;,              '" 。 $密码。 "&#39 ;,              '" 。 $ IP。 "&#39 ;,              '" 。 $ total_entry。 "&#39 ;,              '" 。 $ average_entry。 "&#39 ;,              '" 。 $ date_of_registration。 "&#39 ;,              '" 。 $ lastactive。 "&#39 ;,              '" 。 $ account_state。 "')&#34 ;;

// Get above inserted id here in variable 

$last_id = $this->db->insert_id();

//adds the basic entry to the database   
$data = array(
    'message' => $message,
    'picture' => $picture,
    'uid' => $last_id, //write $last_id here instead $uid
    'time' => $date_of_registration,
);

$this->db->insert('entries', $data);

它应该可行