简体   繁体   中英

PHP transactions and mysqli_insert_id

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 (ie 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM