exec-6ren">
gpt4 book ai didi

php - 如果 PDO 事务失败,如何重定向到一个页面?

转载 作者:行者123 更新时间:2023-11-29 06:31:20 25 4
gpt4 key购买 nike

我需要重定向到一个单独的页面来显示错误。 header("位置:errorpage.php?errorcode=11");之后似乎不起作用。

<?php
$db = new PDO("mysql:host=localhost;dbname=mydbase;charset=utf8", "user", "password");
try {
$db->beginTransaction();

$db->exec("SOME QUERY");

$db->commit();
}

catch(PDOException $ex) {
$db->rollBack();
//Something went wrong so I need to redirect
header("Location: errorpage.php?errorcode=11");
}

最佳答案

PDO's error handling 有点不寻常。它具有抛出真正的异常、发出 PHP 警告或保持沉默的模式。

默认是静音。这里发生的是,没有异常被抛出,因为你没有配置 PDO 来抛出异常。因此,catch block 永远不会被输入,header() 也永远不会被调用。设置您的 $db 对象以抛出异常:

// Ensure PHP's native error handling is showing
// on screen (to catch problems with header() itself)
error_reporting(E_ALL);
// Always in development, disabled in production
ini_set('display_errors', 1);

$db = new PDO("mysql:host=localhost;dbname=mydbase;charset=utf8", "user", "password");

// Turn on exceptions for PDO so the try/catch is meaningful
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try {
$db->beginTransaction();
$db->exec("SOME QUERY");
$db->commit();
}

catch(PDOException $ex) {
$db->rollBack();
//Something went wrong so I need to redirect
header("Location: errorpage.php?errorcode=11");
// Always make an explicit call to exit() after a redirection header.
exit();
}

关于PDO::exec():

我知道这是示例代码,但 exec() 通常不是正确的使用方法。如果您正在执行 DDL 语句,事务将不起作用,因为 MySQL 不支持它,如果您正在对任何用户输入执行 INSERT/UPDATE/DELETE 之类的操作,您应该执行 prepare()/execute()而是创建一个注入(inject)安全的准备好的语句。

关于php - 如果 PDO 事务失败,如何重定向到一个页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27755963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com