我有一个注册页面,基本上我需要插入到4个表中的数据。 我是新来的PDO和我对某事感到困惑。
基本上,如果任何插件的失败,我不希望任何添加到数据库中,这似乎很简单。
我的困惑是,我需要先插入用户的用户名,电子邮件,我的密码等users
表,所以我可以(不知道如何)的UID MySQL已经使用PDO给我的用户(自动由MySQL递增)。 我需要的用户UID MySQL的给我的用户在其他表为其他表所需要的UID所以一切都是正确连接在一起。 我的表是InnoDB和我有外键从users_profiles(user_uid)去,users_status(user_uid),users_roles(user_uid)到users.user_uid所以他们都连接在一起。
但在同一时间,我想确保,例如,如果插入数据后, users
表(这样我就可以得到UID MySQL的给用户),如果任何其他刀片的失败,它会删除插入数据users
表。
我认为这是最好的,我表明我的代码; 我注释掉的代码,在代码中可能更容易理解已经解释。
// Begin our transaction, we need to insert data into 4 tables:
// users, users_status, users_roles, users_profiles
// connect to database
$dbh = sql_con();
// begin transaction
$dbh->beginTransaction();
try {
// this query inserts data into the `users` table
$stmt = $dbh->prepare('
INSERT INTO `users`
(users_status, user_login, user_pass, user_email, user_registered)
VALUES
(?, ?, ?, ?, NOW())');
$stmt->bindParam(1, $userstatus, PDO::PARAM_STR);
$stmt->bindParam(2, $username, PDO::PARAM_STR);
$stmt->bindParam(3, $HashedPassword, PDO::PARAM_STR);
$stmt->bindParam(4, $email, PDO::PARAM_STR);
$stmt->execute();
// get user_uid from insert for use in other tables below
$lastInsertID = $dbh->lastInsertId();
// this query inserts data into the `users_status` table
$stmt = $dbh->prepare('
INSERT INTO `users_status`
(user_uid, user_activation_key)
VALUES
(?, ?)');
$stmt->bindParam(1, $lastInsertID, PDO::PARAM_STR);
$stmt->bindParam(2, $activationkey, PDO::PARAM_STR);
$stmt->execute();
// this query inserts data into the `users_roles` table
$stmt = $dbh->prepare('
INSERT INTO `users_roles`
(user_uid, user_role)
VALUES
(?, ?)');
$stmt->bindParam(1, $lastInsertID, PDO::PARAM_STR);
$stmt->bindParam(2, SUBSCRIBER_ROLE, PDO::PARAM_STR);
$stmt->execute();
// this query inserts data into the `users_profiles` table
$stmt = $dbh->prepare('
INSERT INTO `users_profiles`
(user_uid)
VALUES
(?)');
$stmt->bindParam(1, $lastInsertID, PDO::PARAM_STR);
$stmt->execute();
// commit transaction
$dbh->commit();
} // any errors from the above database queries will be catched
catch (PDOException $e) {
// roll back transaction
$dbh->rollback();
// log any errors to file
ExceptionErrorHandler($e);
require_once($footer_inc);
exit;
}
我是新来的PDO和可能存在的错误或问题上面我还没有注意到,因为我还不能测试,直到我找出我的问题。
1)我需要知道我可以在用户表中首先将用户的数据,所以我可以得到UID MySQL的给我的用户
2)然后得到uid作为我需要它的其他表
3),但如果插入到用户表中的数据也从用户表中删除藏汉后,不管是什么原因查询失败的同时。
更新:
我更新了上面的代码,以反映被帮助的成员提供改变。