我有以下表格:
thread: id, title, content, created
thread_tags: tag_id, thread_id
tag: id, name
author_threads: thread_id, author_id
为了创建一个线程,必须填写所有这些字段(显然ID会自动递增)。我知道我可以使用SQL TRANSACTIONS来确保所有这些都被填充或者没有,但是我如何从最后一个sql语句填写tag_id,thread_id,author_id和thread_id(在author_threads中)?没有事务,我会使用mysqli_last_insert_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;");
答案 0 :(得分:1)
对我而言,您似乎已经知道答案:使用mysqli_insert_id()
或SELECT LAST_INSERT_ID()
。在事务中使用它们应该没有问题:
如果某些内容失败,请回滚该交易,您将什么都没有。