【问题标题】:pdo catch and output mysql errors [duplicate]pdo捕获并输出mysql错误[重复]
【发布时间】:2022-01-17 14:52:30
【问题描述】:

我有一个使用 PDO 执行的插入语句。插入效果很好,但是如果出现错误,我希望将其显示给用户。

我有下面的 try-catch 块。

try{ 
    $insertuser = $db->prepare('INSERT INTO `she_she`.`Persons` (`idnumber`,`addedby`,`firstname`, `middlename`, `surname`, `fullname`, `gender`, `birthdate`, `homelanguage`, `department`, `employeetype`, `employeestatus`) VALUES  (?,?,?,?,?,?,?,?,?,?,?,?)'); 
    $insertuser->execute(array($idnumber,$user,$firstname, $middlename, $surname, $fullname, $gender, $birthdate, $language, $department, $employmenttype, $personstatus));  
} 
catch(PDOException $exception){ 
    return $exception; 
} 

如果查询失败,或者说是重复的 IDNumber,我希望将其显示给用户。

如果我只是尝试回显变量 $exception 它不起作用。

我想将 MySQL 错误返回给用户。

【问题讨论】:

  • $exception 将是 PDOException 类型的对象,其众多属性中的两个将是 mysql 错误代码和错误消息。

标签: php pdo try-catch


【解决方案1】:

默认情况下,PDO 不处于会显示错误的状态。您需要在数据库连接中提供以下内容

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

更多信息可以看Here

【讨论】:

  • 谢谢。如果我将错误模式设置为ERRMODE_WARNING,它会在页面顶部返回警告,我如何将其设置为变量的值并将其返回到页面上我想要的位置。谢谢
  • 在您的 catch 块中,您可以将 $exception 设置为不同的变量以供以后使用。 catch(PDOException $exception){ $error = $exception->getMessage(); } //later in code echo "An Error has occurred " . $error; 或类似的东西。
【解决方案2】:

1.在你的db连接后添加ERRMODE_EXCEPTION模式:

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

2.而且您必须对所有 mysql 查询使用 try{} catch{} 方法。像这样:

try {
    $SQL = "DELETE FROM items WHERE item_id=:item_id";
    $m = $dbh->prepare($SQL);
    $m->bindParam(':item_id', $item_id, PDO::PARAM_INT);
    $m->execute();
    //success
    $return = "Your success message.";
}
catch (PDOException $e) {
    //error
    $return = "Your fail message: " . $e->getMessage();
}

【讨论】:

    【解决方案3】:

    你应该使用这个:

    return $exception->getMessage();
    

    见异常类文档页面:

    http://www.php.net/manual/en/exception.getmessage.php

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 2012-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多