我处于需要在查询中插入 2 个表的情况。我在网上搜索过,找不到解决方案。我想要做的是在
user
表中插入值并同时在 profile
中插入值。我可以一个接一个地做,但我读到它效率不高,被认为是糟糕的编码技术。
当前代码:
$statement = $db->prepare("
BEGIN;
INSERT INTO `user`(`username`, `email`, `password_hashed`, `fname`, `lname`, `dob`, `agreement`, `gender`, `access_token`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
INSERT INTO `profile_picture`(`owner`) VALUES (LAST_INSERT_ID());
COMMIT;
");
if($statement) {
$statement->bind_param("ssssssiss", $username, $email, $hashedPassword, $fname, $lname, $dob, $agreement, $gender, $access_token);
$statement->execute();
$statement->close();
echo "DONE";
exit();
}
else printf("Error: %s.\n", $db->error);
try {
$db->beginTransaction();
$stmt = $db->prepare("INSERT INTO `user`(`username`, `email`, `password_hashed`, `fname`, `lname`, `dob`, `agreement`, `gender`, `access_token`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssssiss", $username, $email, $hashedPassword, $fname, $lname, $dob, $agreement, $gender, $access_token);
$stmt->execute();
$stmt = $db->prepare("ANOTHER QUERY");
$stmt->bind_param(...)
$stmt->execute();
$db->commit();
} catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
throw $ex->getMessage();
}
第一条语句执行后,您可以使用以下命令从 PHP 访问 insertID:$last_id = $db->lastInsertId();希望这有帮助!