我还没有找到使用MySQL事务的PHP文件的正常示例.你能给我举个简单的例子吗?

还有一个问题.我已经做了很多编程,没有使用事务.我可以在header.php中加入一个PHP函数或类似的东西,如果一个mysql_query失败了,那么其他的也失败了吗?


我想我已经弄明白了,对吗?

mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");

$a1 = mysql_query("INSERT INTO rarara (l_id) VALUES('1')");
$a2 = mysql_query("INSERT INTO rarara (l_id) VALUES('2')");

if ($a1 and $a2) {
    mysql_query("COMMIT");
} else {        
    mysql_query("ROLLBACK");
}

推荐答案

我在处理事务时通常使用的 idea 如下:

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();
    
    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');
    
    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (\Throwable $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
    throw $e; // but the error must be handled anyway
}

Note that, with this idea, if a query fails, an Exception must be thrown:
  • PDO can do that, depending on how you configure it
  • 否则,使用其他API时,您可能必须测试用于执行查询的函数的结果,然后自己抛出异常.

Unfortunately, there is no magic involved. You cannot just put an instruction somewhere and have transactions done automatically: you still have to specific which group of queries must be executed in a transaction.

例如,通常在事务(before the 100)之前会有两个查询,在事务(after either 101 or 102)之后会有两个查询,并且无论事务(or not)中发生了什么,您都希望执行这些查询.

Php相关问答推荐

条纹 checkout :订阅试用版和额外付款(add_invoice_items)错误

Laravel 11发送邮箱时奇怪的未定义数组键名称

Laravel 9如何过滤$的项目与结果?

管理员订单列表中的自定义列与WooCommerce 8.6.1一起消失

在WooCommerce管理订单列表中显示项目总权重

在PHP中循环访问多维数组,并按组显示内容

为什么本地主机(Xampp)上的laravel运行速度比普通html站点慢?

FlySystem v3:使用本地适配器时出现问题

在WooCommerce Admin产品列表自定义列中显示来自元数据的统计数据

Laravel withOnly不限制查询

将 PHP 版本更改为 8.1,但 WordPress 认为我们正在使用版本 7.4?

Woocommerce 中为空时隐藏显示变体自定义字段数据

如何正确判断 PHP 是否已正确配置为使用 DOMDocument?

如何在 PHP 中对具有相同数组值的值求和

提交仅包含活动详细信息选项卡表单的主表单

如何在自定义消息中包含 WooCommerce 选定的产品变体详细信息

使用 PHP 正则表达式从仅包含具有现有顺序的顶级标签的 XML 文档中搜索和创建数组

为什么 AJAX 请求没有通过 is_ajax_request() codeigniter 的条件?

如何在 php/laravel 中获取元素在数组中的位置

图像不会显示在生产中的 Laravel 应用程序中