I have the following tables:
thread: id, title, content, created
thread_tags: tag_id, thread_id
tag: id, name
author_threads: thread_id, author_id
This is what I normally do to insert values into all of these fields (some steps have been omitted for simplicity):
$sql_thread = "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)")
I want to make sure that all of this occurs or none of it occurs (i.e. the process of creating a thread). How can I code this to use transactions? Or any other way to ensure all of it occurs?
- Convert your tables to innodb (if they aren't already)
- Perform
mysqli_autocommit($link, FALSE);
before all your queries - Perform
mysqli_commit($link);
after all your queries, if they have performed successfully - If any query failed - perform
mysqli_rollback($link);
and stop execution
More details at:
- http://ru.php.net/manual/en/mysqli.commit.php
- http://ru.php.net/manual/en/mysqli.rollback.php
精彩评论