PHP 事务和 mysqli_insert_id

标签 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. 将您的表转换为 innodb(如果尚未转换)
  2. 在所有查询之前执行 mysqli_autocommit($link, FALSE);
  3. 在所有查询之后执行 mysqli_commit($link);,如果它们已成功执行
  4. 如果任何查询失败 - 执行 mysqli_rollback($link); 并停止执行

更多详情:

关于PHP 事务和 mysqli_insert_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385325/

相关文章:

javascript - 在请求中使用数据 URI 发送的 Canvas 图像在保存后损坏

php - MySQL:查询另一个查询结果并返回两个结果?

MySQL 比较 'LEFT JOIN IS NULL' 与 'GROUP BY'

mysql - Perl DBI - 并行事务

transactions - SAGA代表什么?

java - 事务回滚时如何返回不同的值?

java - 使用HttpClient进行登录认证

php - 无法读取 null 的属性 'replaceWith' - ajax 调用

php - 如何使用 PHP 下载生成的 pdf 文件?

java - 如何在 Java 中检查日期时间之前和之后的日期,以了解 MySQL 中的 UTC 日期,但对于多个时区?