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?

Oct 28, 2021 pm 04:54 PM
pdo php

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();
    }
?>
Copy after login

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));
Copy after login

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();
    }
?>
Copy after login

输出结果:

How to handle errors in PDO for PHP database learning?

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

<strong><span style="max-width:90%">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();
    }
?>
Copy after login

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

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles