Error and excep...LOGIN

Error and exception handling

Error exception handling mode: PDO::ERRMODE_EXCEPTION

## As an attachment for setting the error code, PDO A PDOException will be thrown and its properties will be set to reflect the error code and error message. This setting is also very useful when debugging, because it will effectively "blow up" the error point in the script, very quickly pointing to a possible error area in your code. (Remember: if an exception causes the script to abort, the transaction will automatically roll back.)

Exception mode is also very useful because you can use a clearer structure than the traditional PHP-style error handling structure. Errors use less code and nesting than using quiet mode, and can more explicitly check the return value of each database access.

微信图片_20180305114759.png

The completed code is as follows:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/5 0005
 * Time: 上午 9:23
 */
header("Content-Type:text/html;charset=utf-8");
//mysql:host:localhost;port=3306;dbname=php;charset=utf-8
$dbms='mysql';
$host='localhost';
$port='3306';
$dbname='php';
$charset='utf-8';
//用户名与密码
$user='root';
$pwd='root';
$dsn="$dbms:host=$host;port=$port;dbname=$dbname;charset=$charset";
try{
    $pdo=new PDO($dsn,$user,$pwd);
    //设置错误处理
//    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT);   //0 默认模式
//    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);  //1  警告处理模式
    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//2
//    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ATTR_ERRMODE);     //3
    //预处理sql语句
//    $stmt=$pdo->prepare("insert into book(name,author)values(?,?)");
    $stmt=$pdo->prepare("select *from phpbook");
    $stmt->execute();
    //获取错误信息
    $code=$stmt->errorCode();
    $info=$stmt->errorInfo();
    //输出相关信息
    print_r("错误码:".$code."<br>");
    print_r("错误信息:");
    print_r($info);
}catch (PDOException $exception){
    echo $exception->getMessage().'<br>';
}

Running result display:

微信图片_20180305114907.pngNext Section

<?php echo "PDO异常处理模式";
submitReset Code
ChapterCourseware