Home >Backend Development >PHP Problem >How to handle errors in PDO for PHP database learning?

How to handle errors in PDO for PHP database learning?

WBOY
WBOYOriginal
2021-10-28 16:54:022242browse

In the previous article, I brought you "How to use PDO to obtain query results in PHP database learning?" ", which introduces in detail the relevant knowledge on how to use PDO to obtain query results. In this article, let's take a look at how to handle PDO errors in PHP. I hope it will be helpful to everyone!

How to handle errors in PDO for PHP database learning?

In the previous study, we have learned to obtain query results through PDO. Next, we need to learn about PDO error handling. There are two acquisition methods in PDO. The error information methods in the program are errorCode() method and errorInfo() method. Next, let’s take a look at the applications of these two methods.

Before understanding how the errorCode() method and errorInfo() method handle errors, let's first take a look at the error handling mode in PDO.

PDO error handling mode

There are three different error handling modes provided in PDO, which can not only meet the Different styles of programming can also adjust the way extensions handle errors. Then I will introduce to you these three different error handling methods.

  • <span style="font-size: 16px;">##PDO::ERRMODE_SILENT<strong></strong></span><span style="font-size: 16px;"> <strong></strong></span>

PDO::ERRMODE_SILENT represents the default mode. In this case, when an error occurs, PDO will simply set the error code and will not perform any other operations. , you can also use the two methods PDO::errorCode() and PDO::errorInfo() to check statements and check database objects.

What we need to note is that if the error occurs because of the calling statement object, then the PDOStatement::errorCode() or PDOStatement::errorInfo() method of this object can be called. If the error occurs due to calling a database object, you can call the PDOStatement::errorCode() or PDOStatement::errorInfo() methods on the database object.


  • ##PDO::ERRMODE_WARNING <span style="font-size: 16px;"><strong></strong></span><span style="font-size: 16px;"></span>

  • PDO::ERRMODE_WARNING mode can set the error code. Of course, in addition to setting the error code, PDO will also send a message. This message is a very traditional E_WARNING message. When we need to debug or test, we don't want to interrupt the program but want to figure out what went wrong. PDO::ERRMODE_WARNING It’s time for this mode to come into play


  • ##PDO::ERRMODE_EXCEPTION <span style="font-size: 16px;"><strong> </strong></span>

    PDO::ERRMODE_EXCEPTION mode can also set error codes. In addition to setting error codes at first glance, PDO can also throw a PDOException exception class and set its properties to reflect error codes. and error messages. The PDO::ERRMODE_EXCEPTION mode is also very useful when debugging. It can point out potential problematic areas in the code very quickly, because it effectively magnifies the point in the script where the error occurs.

PDO uses
SQL-92 SQLSTATE

to standardize error code strings, and different PDO drivers are responsible for mapping their native codes to the appropriate SQLSTATE codes.

PDO::errorCode() The method returns a single SQLSTATE code. If you need more detailed information about this error, PDO also provides a PDO::errorInfo()

method to return an error that includes the SQLSTATE code, the specific driver error code, and the driver. Array of strings.

Another very useful effect of exception mode is that you can build your own error handling more clearly than traditional PHP-style warnings, and compared to silent mode and explicitly checking the return of each database call value, exception pattern requires less code/nesting.
Next, let’s look at creating a PDO instance and setting the error mode through an example. The example is as follows:

<?php
    $dsn  = &#39;mysql:dbname=test;host=127.0.0.1&#39;;
    $user = &#39;root&#39;;
    $pwd  = &#39;root&#39;;
    try {
        $pdo = new PDO($dsn, $user, $pwd);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo &#39;Connection failed: &#39; . $e->getMessage();
    }
?>

In the above example, the error mode is set through the

PDO::setAttribute()

method. In addition to setting the error mode in this way, it can also be set when creating a PDO instance. Error mode

Examples are as follows:

$pdo = new PDO($dsn, $user, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

The above are the three error handling modes of PDO. Next, let’s take a look at the PDO::errorCode() method.

PDO::errorCode()<strong><span style="font-size: 20px;"></span>## Method </strong>PDO::errorCode() The method is mostly used to obtain error codes that occur when operating database handles. These error codes are called SQLSTATE codes.

PDO::errorCode() 方法可以返回一个 SQLSTATE,一个由 5 个字母或数字组成的在 ANSI SQL 标准中定义的标识符。 简单可以理解成,一个 SQLSTATE 由前面两个字符的类值和后面三个字符的子类值组成。

接下来我们通过示例来看一下通过 PDO 连接数据库,并通过 errorCode() 方法获取错误代码。

示例如下:

<?php
    $dsn  = &#39;mysql:dbname=test;host=127.0.0.1&#39;;
    $user = &#39;root&#39;;
    $pwd  = &#39;root&#39;;
    try {
        $pdo = new PDO($dsn, $user, $pwd);
        $sql = &#39;select * from user&#39;;
        $res = $pdo -> query($sql);
        echo &#39;errorCode 为:&#39;.$pdo -> errorCode().&#39;<br>&#39;;
        foreach ($res as $key => $value) {
            echo &#39;序号:&#39;.$value[&#39;id&#39;].&#39;; 姓名:&#39;.$value[&#39;name&#39;].&#39;; 年龄:&#39;.$value[&#39;age&#39;].&#39;; 性别:&#39;.$value[&#39;sex&#39;].&#39;<br>&#39;;
        }
    } catch (PDOException $e) {
        echo &#39;Connection failed: &#39; . $e->getMessage();
    }
?>

输出结果:

How to handle errors in PDO for PHP database learning?

上述结果便是通过 errorCode() 方法获取错误代码。接下来我们看一下最后一种方法PDO::errorInfo() 方法。

<strong><span style="font-size: 20px;">PDO::errorInfo() </span></strong>方法

PDO::errorInfo() 方法与PDO::errorCode() 方法一样都是用于获取操作数据库句柄时所发生的错误信息。

不同的是errorInfo() 方法的返回值为一个数组,它包含了相关的错误信息。

接下来我们通过示例来看一下使用 PDO 中的 query 方法完成数据查询操作,并通过 errorInfo() 方法获取错误信息。

示例如下:

<?php
    $dsn  = &#39;mysql:dbname=test;host=127.0.0.1&#39;;
    $user = &#39;root&#39;;
    $pwd  = &#39;root&#39;;
    try {
        $pdo = new PDO($dsn, $user, $pwd);
        // $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = &#39;select * from userr&#39;;
        $res = $pdo -> query($sql);
        echo &#39;errorInfo 为:<br>&#39;;
        print_r($pdo -> errorInfo());
    } catch (PDOException $e) {
        echo &#39;Connection failed: &#39; . $e->getMessage();
    }
?>

上述示例中,我们查询了一个不存在的数据库,输出结果:

How to handle errors in PDO for PHP database learning?

其中我们需要注意的是:PDO 和 PDOStatement 对象中都有 errorCode() 和 errorInfo() 方法,如果没有任何错误,errorCode() 返回的是 00000;否则就会返回一些错误代码。而 errorInfo() 返回的是一个数组,包括 PHP 定义的错误代码和 MySQL 的错误代码及错误信息。

大家如果感兴趣的话,可以点击《PHP视频教程》进行更多关于PHP知识的学习。

The above is the detailed content of How to handle errors in PDO for PHP database learning?. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:What does .= in php mean?Next article:What does .= in php mean?