Home  >  Article  >  Backend Development  >  Detailed explanation of php PDO exception handling

Detailed explanation of php PDO exception handling

高洛峰
高洛峰Original
2016-12-12 09:45:311584browse

Exception handling:

PHP: The default is to report errors directly

MYSQL: The default is silent mode. When an error occurs, an error will be reported directly, and error handling will become quite troublesome. Later, when an error occurs, the error information will no longer be output directly and will be placed in a class object (PDOException)

pdo exception handling settings:

Set PDO::ATTR_ERRMODE, which has the following three values:

PDO ::ERRMODE_SILENT: The default mode does not actively report errors. You need to actively obtain error information in the form of $pdo->errorInfo().

PDO::ERRMODE_WARNING: Raise an E_WARNING error and actively report an error

PDO::ERRMODE_EXCEPTION: Actively throw exceptions, and you need to use try{}cath(){} to output error information.

Example:

Method 1:

<?php
//默认是不提示的 需要用 errorCode() errorInfo();
try{
  $pdo = new PDO("mysql:host=localhost;dbname=jikexueyuan","root","");
  //下面这句是默认设置,有无均可
  $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT);
}catch(PDOException $e){
  die("数据库连接失败".$e->getMessage());
}
$sql = "insert into stuu values(null,&#39;jike&#39;,&#39;w&#39;,55)";
$res = $pdo->exec($sql);
if($res){
  echo "OK";
}else{
  echo $pdo->errorCode();
  print_r($pdo->errorInfo());
}

Method 2:

<?php
try{
  $pdo = new PDO("mysql:host=localhost;dbname=jikexueyuan","root","");
  //主动以警告的形式报错
  $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
}catch(PDOException $e){
  die("数据库连接失败".$e->getMessage());
}
$sql = "insert into stuu values(null,&#39;jike&#39;,&#39;w&#39;,55)";
//若有错误直接在浏览器页面中显示错误信息
$res = $pdo->exec($sql);

Method 3:

<?php
try{
  $pdo = new PDO("mysql:host=localhost;dbname=jikexueyuan","root","");
  //主动抛出异常
  $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
  die("数据库连接失败".$e->getMessage());
}
$sql = "insert into stuu values(null,&#39;jike&#39;,&#39;w&#39;,55)";
//用try{}catch(){}抓取异常
try{
  $res = $pdo->exec($sql);
}catch(PDOException $e){
  echo $e->getMessage();
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn