如何处理 PDO 异常

2022-08-30 21:44:10

我正在尝试在php上使用class,但是我很难找到正确的方法来处理错误,我已经写了这个代码:PDO

<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type


$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";


try {

$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";

$statement = $connection->prepare ($sql);

$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);

$status = $statement->execute ();

} catch (PDOException $e) {
    print $e->getMessage ();
}

print $status; // it returns a null value, and no errors are reported

?>

这部分代码不报告错误,但它根本不起作用,底部的var返回一个空值。$status

有人可以帮我找到我错的地方吗?


答案 1

PDO 不会引发异常,除非您告诉它。你有没有跑过:

$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

在 PDO 对象上?


答案 2

您可以在连接 mysql 时添加一次属性。

function connect($dsn, $user, $password){
    try {
        $dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
        exit;
    }
    }

谢谢


推荐