[英]MySQLi: How to insert into multiple tables with prepared statements
I am in a situation where I need to insert into 2 tables in a query. 我处于需要在查询中插入2个表的情况。 I've searched around web and could not find solution. 我在网上搜索,找不到解决方案。 What I want to do is insert values in user
table & insert values in profile
simultaneously. 我想做的是同时在user
表中插入值并在profile
同时插入值。 I could do one after the other way but I've read that it is not efficient and is considered as poor coding technique. 我可以采用另一种方法,但是我已经读到它效率不高,被认为是较差的编码技术。
Current Code: 当前代码:
$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);
I had issues with this trying to copy answers like Frank's. 我在尝试复制像弗兰克的答案时遇到问题。 The proper way to do it is: 正确的方法是:
<?php
try {
$db->beginTransaction();
$stmt = $db->prepare("QUERY");
$stmt->execute();
$stmt = $db->prepare("ANOTHER QUERY??");
$stmt->execute();
$db->commit();
}
catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
echo $ex->getMessage();
}
After the first statement is executed, you can then gain access to the insertID from PHP using the following: $last_id = $db->lastInsertId(); 执行第一条语句后,您可以使用以下命令从PHP获得对insertID的访问:$ last_id = $ db-> lastInsertId();
Hope this helps! 希望这可以帮助!
Maybe this one can help you: MySQL Insert into multiple tables? 也许这可以帮助您: MySQL插入多个表?
I think you need a statement like this: 我认为您需要这样的声明:
BEGIN;
INSERT INTO user(column_a,column_b) VALUES('value_a','value b');
INSERT INTO profile(column_x,column_y) VALUES('value_x','value_y');
COMMIT;
If you need the last id from user table, you can use the LAST_INSERT_ID() function. 如果需要用户表中的最后一个ID,则可以使用LAST_INSERT_ID()函数。
尝试使用mysqli_multi_query,请检查此链接,例如http://blog.ulf-wendel.de/2011/using-mysql-multiple-statements-with-php-mysqli/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.