我正在尝试插入两个表中。在第一个表上,插入基本用户信息。在第二张表上,我需要用户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中执行此操作的最佳方法是什么?
谢谢
最佳答案
您应该使用$ this-> db-> insert_id()作为$ data数组中的uid值,因此,它类似于:
//将基本的用户信息添加到用户数据库
$ sql =“插入INTO用户(名字,姓氏,用户名,电子邮件,密码,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。”')“;
// 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);
它应该工作