How to handle errors in PDO for PHP database learning?
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!
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.
##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
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.<span style="font-size: 16px;"><strong> </strong></span>
PDO uses
SQL-92 SQLSTATE
PDO::errorCode() The method returns a single
SQLSTATE code.
If you need more detailed information about this error, PDO also provides a
PDO::errorInfo()
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 = 'mysql:dbname=test;host=127.0.0.1'; $user = 'root'; $pwd = 'root'; try { $pdo = new PDO($dsn, $user, $pwd); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
PDO::setAttribute()
method. In addition to setting the error mode in this way, it can also be set when creating a PDO instance. Error modeExamples are as follows:
$pdo = new PDO($dsn, $user, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
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 = 'mysql:dbname=test;host=127.0.0.1'; $user = 'root'; $pwd = 'root'; try { $pdo = new PDO($dsn, $user, $pwd); $sql = 'select * from user'; $res = $pdo -> query($sql); echo 'errorCode 为:'.$pdo -> errorCode().'<br>'; foreach ($res as $key => $value) { echo '序号:'.$value['id'].'; 姓名:'.$value['name'].'; 年龄:'.$value['age'].'; 性别:'.$value['sex'].'<br>'; } } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
输出结果:
上述结果便是通过 errorCode() 方法获取错误代码。接下来我们看一下最后一种方法PDO::errorInfo() 方法。
<strong><span style="max-width:90%">PDO::errorInfo() </span></strong>
方法
PDO::errorInfo()
方法与PDO::errorCode()
方法一样都是用于获取操作数据库句柄时所发生的错误信息。
不同的是errorInfo() 方法的返回值为一个数组,它包含了相关的错误信息。
接下来我们通过示例来看一下使用 PDO 中的 query 方法完成数据查询操作,并通过 errorInfo() 方法获取错误信息。
示例如下:
<?php $dsn = 'mysql:dbname=test;host=127.0.0.1'; $user = 'root'; $pwd = 'root'; try { $pdo = new PDO($dsn, $user, $pwd); // $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = 'select * from userr'; $res = $pdo -> query($sql); echo 'errorInfo 为:<br>'; print_r($pdo -> errorInfo()); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ?>
上述示例中,我们查询了一个不存在的数据库,输出结果:
其中我们需要注意的是: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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,

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

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 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.
