开发者

PHP transactions and mysqli_insert_id

开发者 https://www.devze.com 2023-02-19 07:12 出处:网络
I have the following tables: thread: id, title, content, created thread_tags: tag_id, thread_id tag: id, name

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?


  1. Convert your tables to innodb (if they aren't already)
  2. Perform mysqli_autocommit($link, FALSE); before all your queries
  3. Perform mysqli_commit($link); after all your queries, if they have performed successfully
  4. 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
0

精彩评论

暂无评论...
验证码 换一张
取 消