PHP事务和mysqli_insert_id

时间:2011-03-22 00:24:20

标签: php mysql transactions

我有以下表格:

thread: id, title, content, created
thread_tags: tag_id, thread_id
tag: id, name
author_threads: thread_id, author_id

我通常会将值插入所有这些字段(为简单起见,省略了一些步骤):

  $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)")

我想确保所有这些都发生或者没有发生(即创建线程的过程)。如何编写此代码以使用事务?或者以其他方式确保所有这些都发生?

1 个答案:

答案 0 :(得分:4)

  1. 将您的表格转换为innodb(如果它们尚未存在)
  2. 在所有查询之前执行mysqli_autocommit($link, FALSE);
  3. 在所有查询后执行mysqli_commit($link);,如果他们已成功执行
  4. 如果任何查询失败 - 执行mysqli_rollback($link);并停止执行
  5. 更多详情: