Error handling of PDO in PHP_PHP tutorial
Object-oriented approach
Let’s first look at the handling of connection errors, etc. The error handling of PDO in PHP is handled in an object-oriented approach:
try {
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass) ;
$db = null;
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "
";
die();
}
?>
Here we use the object-oriented exception handling feature of PHP 5. If there is an exception, PDOException is initialized to initialize an exception class.
Attribute structure of PDOException exception class:
class PDOException extends Exception
{
public $errorInfo = null; // Error message, you can call PDO::errorInfo() or PDOStatement::errorInfo() to access
protected $message; // Exception message, You can try Exception::getMessage() to access
protected $code; // SQL status error code, you can use Exception::getCode() to access
}
?>
This exception handling class is integrated with the built-in exception handling class of PHP 5. Let’s take a brief look at the built-in exception handling class structure of PHP 5:
class Exception
{
// Attributes
protected $message = 'Unknown exception'; // Exception message
protected $code = 0; //User-defined exception code
protected $file; //The file name where the exception occurred
protected $line; //The code line number where the exception occurred
//Method
final function getMessage(); // Return exception information
final function getCode(); // Return exception code
final function getFile(); // Return the file name where the exception occurred
final function getLine (); // Return the code line number where the exception occurred
final function getTrace(); // backtrace() array
final function getTraceAsString(); // getTrace() information formatted into a string
}
?>
Correspondingly, getFile() and getLine() can be appropriately called in the code to locate errors and make debugging more convenient.
Use the process-oriented approach
Look at the code first:
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$rs = $db->query("SELECT aa,bb,cc FROM foo ");
if ($db->errorCode() != '00000'){
print_r($db->errorInfo());
exit;
}
$arr = $rs->fetchAll();
print_r($arr);
$db = null;
?>
PDO and PDOStatement objects have errorCode () and errorInfo() methods, if there is no error, errorCode() returns: 00000, otherwise some error code will be returned. errorInfo() returns an array, including error codes defined by PHP and MySQL error codes and error messages. The array structure is as follows:
Array
(
[0] => 42S22
[1 ] => 1054
[2] => Unknown column 'aaa' in 'field list'
)
After each query is executed, the result of errorCode() is the latest, so we can It's easy to control the error message display yourself.
What should I do if I encounter errors again during PHP and database development using PDO? Treat it as above.
11.3.4 PDO error handling
PDO provides two methods to obtain error information in the program, one is the errorCode() method; the other is errorInfo ()method.
1. errorCode() method
The errorCode() method is used to obtain error codes that occur when operating database handles. These error codes are called SQLSTATE codes. The syntax format of this method is as follows:
01 string errorCode (void) The return value of the errorCode() method is a SQLSTATE. SQLSTATE is a code composed of 5 numbers and letters. The following is an example of using the errorCode() method:
[Program 11-17] CD code11pdoerrorCode.php
$dsn = 'mysql:dbname=shop;host=localhost';
$user_name = 'root';
$user_psw = ' root';
$pdo = new PDO($dsn, $user_name, $user_psw);
$pdo->exec("update mytable set age=28 where id=1 ");//table mytable
echo "errorCode is: ".$pdo->errorCode();
?>
The error code output by the above code is shown in Figure 11-13.

2. errorInfo() method
errorInfo() method is used to obtain error information that occurs when operating a database handle. The syntax format of this method is as follows:
01 array errorInfo (void) errorInfo() method The return value is an array, which contains relevant error information. The sample code using the errorInfo() method is as follows:
[Program 11-18] CD code11pdoerrorInfo.php
$dsn = 'mysql:dbname=shop;host=localhost';
$user_name = 'root';
$user_psw = 'root';
$pdo = new PDO($dsn, $user_name, $user_psw);
$pdo->exec("update mytable set age=28 where id=1 ");//The table mytable does not exist
echo "errorInfo is: ";
print_r($pdo->errorInfo());
?>
The error message output by the above code is shown in Figure 11-14.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
