Php 将数据插入两个或多个表:
我有以下表格:Php 将数据插入两个或多个表:,php,mysql,transactions,Php,Mysql,Transactions,我有以下表格: thread: id, title, content, created thread_tags: tag_id, thread_id tag: id, name author_threads: thread_id, author_id 为了创建线程,必须填写所有这些字段(ID显然会自动递增)。我知道我可以使用SQL事务来确保所有事务都已填充或没有,但是如何从上一条SQL语句中填充标记id、线程id、作者id和线程id(在作者线程中)?如果没有事务,我将使用mysqli\u la
thread: id, title, content, created
thread_tags: tag_id, thread_id
tag: id, name
author_threads: thread_id, author_id
为了创建线程,必须填写所有这些字段(ID显然会自动递增)。我知道我可以使用SQL事务来确保所有事务都已填充或没有,但是如何从上一条SQL语句中填充标记id、线程id、作者id和线程id(在作者线程中)?如果没有事务,我将使用mysqli\u last\u insert\u id
我还应该使用mysqli::multi_query
?基本上,我该如何确保所有这些字段都已填写
哦,我正在使用PHP和MYSQL
编辑:
这样行吗
$sql_thread = "START TRANSACTION;
INSERT INTO thread (title, content)
VALUES ('some title', 'some content')";
# this is normally a loop, as there are more than one tags:
$sql_tags = "INSERT INTO tag (name)
VALUES ('onetag')";
# normally I would check the return value
mysqli_query($link, $sql_thread);
# get the thread id:
$thread_id = mysqli_insert_id($link);
mysqli_query($link, $sql_tags);
# get the tag id:
$tag_id = mysqli_insert_id($link);
# insert into thread_tags:
mysqli_query($link, "INSERT INTO thread_tags (thread_id, tag_id) VALUES ($thread_id, $tag_id)");
# insert into author_threads, I already know author_id:
mysqli_query($link, "INSERT INTO author_threads (author_id, thread_id) VALUES ($author_id, $thread_id)
COMMIT;");
在我看来,您似乎已经知道答案:使用
mysqli\u insert\u id()
或SELECT LAST\u insert\u id()
。在交易中使用它们应该没有问题:
- 开始交易
- 插入行
- 获取最后一个插入id
- 插入行,使用外部链接的id
- 提交事务
如果某个操作失败,回滚事务,您将一无所获。为什么不能通过mysqli\u insert\u id()以同样的方式执行此操作?我想您正在寻找
LAST\u insert\u id()
函数。我希望它们全部填写,或者不填写。因此事务?最后一个插入id,是的,我想写它而不是插入id。您如何使用mysqli\u插入id()的事务?我还需要获取两次线程id,逻辑是什么?最后一个插入id仍然在事务内部工作。即使数据尚未提交,当前事务仍可以访问它。要多次使用线程id,只需在创建线程记录后将其设置为某个变量(例如,$thread\u id=mysqli\u insert\u id($db);
)。最简单的方法是尝试。;)您应该将begin/commit分离到它们自己的查询中;我不记得哪一个MySQL函数(如果有的话)支持每个查询多个SQL命令。