mysql表中的多次插入
我在插入 mysql 表时遇到问题。我有 3 个相关表要在保存时插入,但我想确保要么运行所有查询,要么都不运行。我已经在 C# 中完成了此操作,但我想知道如何在 PHP 中完成此操作。
i am facing a problem in inserting into mysql tables. I have 3 related tables to insert on save, but I want to make sure that either all of the queries are run, or none of them. I have done this in C#, but I want to know how i can do it in PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了实现全有或全无的行为,您需要使用事务:
In PHP, if working with [**PDO**][1], you'll want to use the [**`PDO::beginTransaction()`**][2], [**`PDO::commit()`**][3] and [**`PDO::rollback()`**][4] methods.
如果使用MySQLi,您将需要使用
mysqli::commit()
和mysqli::rollback()
-- 使用 禁用自动提交后>mysqli::autocommit()
。To detect if a query has failed, you'll want to :
PDO::setAttribute()
因此当发生错误时会抛出异常。
mysqli::query()
如果查询失败,则返回false
。In order to have a all or nothing behavior, you'll want to use a transaction :
In PHP, if working with [**PDO**][1], you'll want to use the [**`PDO::beginTransaction()`**][2], [**`PDO::commit()`**][3] and [**`PDO::rollback()`**][4] methods.
If working with MySQLi, you'll want to use
mysqli::commit()
andmysqli::rollback()
-- after having disabled autocommit withmysqli::autocommit()
.To detect if a query has failed, you'll want to :
PDO::setAttribute()
so exceptions are thrown when an error occurs.mysqli::query()
returnsfalse
if a query fails.