PHP 与mySQL:实现事务的简单代码 - 提交和提交回滚
我的平台:
PHP 和 PHP mySQL
我的情况:
我正在尝试在我的代码中实现事务。我尝试遵循示例,但没有太大帮助。我正在运行 3 个查询,我想以这样的方式编写一个事务,以便如果任何一个查询失败,整个事务应该回滚。我非常希望有一个简单、高效且非面向对象的 PHP 代码来实现这一目标。先感谢您。
我的 PHP 代码:
//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");
if( $res1 && $res2 && $res3 )
{
//commit --- but how?
}
else
{
//rollback --- but how?
}
MY PLATFORM:
PHP & mySQL
MY SITUATION:
I am trying to implement transactions within my code. I tried to follow examples, but it's not much help. I am running 3 queries and I wanted to write a transaction in such a way so that if any of the query(ies) fail, the whole transaction should roll back. I would really appreciate a simple, efficient and non-object oriented PHP code to achieve this goal. Thank you in advance.
MY PHP CODE:
//db_res calls a custom function that performs a mysql_query on the query
$res1 = db_res("SELECT c1, c2 FROM t1 WHERE c5 = 3");
$res2 = db_res("UPDATE t2 SET c1 = 5 WHERE c2 = 10");
$res3 = db_res("DELETE FROM t3 WHERE c1 = 20");
if( $res1 && $res2 && $res3 )
{
//commit --- but how?
}
else
{
//rollback --- but how?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要使用 mysqli。您可以将事务命令作为查询发出。
因此,对于您的示例:
顺便说一下,如果您正在考虑升级到 mysqli,请不要这样做。升级到 PDO 反而更理智。
You don't need to use mysqli. You can just issue the transaction commands as queries.
So for your example:
By they way if you are thinking about upgrading to mysqli, please don't. Upgrade to PDO instead, it's much more sane.
您需要使用 mysqli 扩展才能使用此功能。
请参阅:autocommit()、commit() 和 rollback()
You need to use the mysqli extension to use this functionality.
See: autocommit(), commit(), and rollback()