Home Backend Development PHP Tutorial Detailed explanation of PDO class in PHP5

Detailed explanation of PDO class in PHP5

May 19, 2018 am 09:14 AM
php php5

This article mainly introduces the detailed explanation of the PDO class in PHP5. Interested friends can refer to it. I hope it will be helpful to everyone.

■What is PDO? The POD (PHP Data Object) extension was added in PHP5. PDO will be used by default to connect to the database in PHP6. All non-PDO extensions will be removed from the extension in PHP6. This extension provides PHP built-in class PDO to access the database. Different databases use the same method name to solve the problem of inconsistent database connections. I configured it for development under windows. ■The goal of PDO

Provide a lightweight, clear, and convenient API
Unify the common features of various different RDBMS libraries, but does not exclude more advanced features.
Provides an optional greater degree of abstraction/compatibility via PHP scripts.

■PDO features:

Performance. PDO learned from the beginning about the successes and failures of scaling existing databases. Because PDO's code is brand new, we have the opportunity to redesign performance from the ground up to take advantage of PHP 5's latest features.
ability. PDO is designed to provide common database functionality as a foundation while providing easy access to the unique features of an RDBMS.
Simple. PDO is designed to make working with databases easy for you. The API doesn't force its way into your code and makes it clear what each function call does.
Extensible at runtime. The PDO extension is modular, enabling you to load drivers for your database backend at runtime without having to recompile or reinstall the entire PHP program. For example, the PDO_OCI extension implements the oracle database API instead of the PDO extension. There are also drivers for MySQL, PostgreSQL, ODBC, and Firebird, with more in development. [separator]


■Installing PDO
Here is the PDO extension for development under WINDOWS. If you want to install and configure it under Linux, please look elsewhere.
Version requirements: php5.1 and later versions are already included in the package; php5.0.x needs to be downloaded from pecl.php.net and placed in your extension library, which is the ext of the folder where PHP is located. folder; the manual says that versions before 5.0 cannot run PDO extensions. Configuration:
Modify your php.ini configuration file so that it supports pdo. (If you don’t understand php.ini, first make it clear that you need to modify the php.ini displayed when calling your phpinfo() function. ) Remove the semicolon in front of extension=php_pdo.dll. The semicolon is the php configuration file comment symbol. This extension is necessary. Further down there are
;extension=php_pdo.dll
;extension=php_pdo_firebird.dll
;extension=php_pdo_informix.dll
;extension=php_pdo_mssql.dll
;extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_oci8.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll corresponding to each extension The databases are:
Driver name Supported databases
PDO_DBLIB FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD Firebird/Interbase 6
PDO_INFORMIX IBM Informix Dynamic Server
PDO_MYSQL MySQL 3.x/4.x
PDO_OCI Oracle Call Interface
PDO_ODBC ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL PostgreSQL
PDO_SQLITE SQLite 3 and SQLite 2
Which database you want to use, just add the corresponding extension Just remove the comment symbol ";" in front of it.

■Using PDO
I assume here that you have installed mysql. If not, please find a way to install it first. Mine is mysql5.0.22, and the passerby in the dark uses MySQL 4.0.26. Also available.
★Database connection:
We use the following example to analyze PDO connection to the database,


$dbms='mysql'; //Database type oracle Using ODI, for developers, if they use different databases, they only need to change this, and there is no need to remember so many functions.
$host='localhost'; //Database host name
$dbName='test' ; //Database used
$user='root'; //Database connection username
$pass=''; //Corresponding password
$dsn="$dbms:host=$host ;dbname=$dbName";
//

try {
$dbh = new PDO($dsn, $user, $pass); //Initializing a PDO object means creating a database Connection object $dbh
echo "Connection successful
";
/*You can also perform a search operation

foreach ($dbh->query('Select * from FOO') as $row) {
                                                                                                                                                                                     print_r($row);
} catch (PDOException $e) {
die ("Error!: " . $e->getMessage() . "
");
}
// By default, this is not a long connection. If you need a long connection to the database, you need to add a parameter at the end: array(PDO::ATTR_PERSISTENT => true), which becomes like this:
$db = new PDO($dsn, $user, $pass , array(PDO::ATTR_PERSISTENT => true));

?>


★Database query:
We have already conducted a query above, we can still Use the following query:
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); //Set attributes
$rs = $db->query("Select * FROM foo");
$rs-> ;setFetchMode(PDO::FETCH_ASSOC);
$result_arr = $rs->fetchAll();
print_r($result_arr);
?>


Because of the above Use the setAttribute() method, put those two parameters, and force the field name to uppercase. The following lists the parameters of PDO::setAttribute(): PDO::ATTR_CASE: Forces the column name to become a format, the details are as follows (second parameter):

PDO::CASE_LOWER: Forces the column name The name is lowercase.

PDO::CASE_NATURAL: The column name is in the original way

PDO::CASE_UPPER: The column name is forced to be uppercase.

PDO::ATTR_ERRMODE: Error Tip.

PDO::ERRMODE_SILENT: Does not display error message, only error code.

PDO::ERRMODE_WARNING: Displays warning error.

PDO::ERRMODE_EXCEPTION: Throw An exception occurred.

PDO::ATTR_ORACLE_NULLS (valid not only for ORACLE, but also for other databases): ) Specify the corresponding value in php for the NULL value returned by the database.

PDO::NULL_NATURAL: unchanged.

PDO::NULL_EMPTY_STRING: Empty string is converted to NULL.

PDO::NULL_TO_STRING: NULL is converted to an empty string .

PDO::ATTR_STRINGIFY_FETCHES: Convert numeric values ​​to strings when fetching. Requires bool.

PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

PDO::ATTR_AUTOCOMMIT (available in OCI, Firebird and MySQL): Whether to autocommit every single statement.

PDO: :MYSQL_ATTR_USE_BUFFERED_QUERY (available in MySQL): Use buffered queries.

$rs->setFetchMode(PDO::FETCH_ASSOC); in the example is PDOStatement::setFetchMode(), a declaration of the return type.
are as follows:
PDO::FETCH_ASSOC -- Associative array form
PDO::FETCH_NUM -- Numeric index array form
PDO::FETCH_BOTH -- Both array forms are available, which is missing Provincial
PDO::FETCH_OBJ -- According to the form of the object, similar to the previous mysql_fetch_object()

For more return type declarations (PDOStatement::method name), see the manual.

★Insert, update, delete data,

$db->exec("Delete FROM `xxxx_menu` where mid=43");


Simple To summarize the above operations:

The query operations are mainly PDO::query(), PDO::exec(), PDO::prepare().
PDO::query() is mainly used for operations that return recorded results, especially Select operations.
PDO::exec() is mainly used for operations that do not return a result set, such as Insert, Update, and Delete For other operations, the result it returns is the number of columns affected by the current operation.
PDO::prepare() is mainly a preprocessing operation. You need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and has a relatively powerful function. This article cannot simply describe it. If you understand, you can refer to the manual and other documents.

The main operations for obtaining the result set are: PDOStatement::fetchColumn(), PDOStatement::fetch(), PDOStatement::fetchALL().
PDOStatement::fetchColumn() is a field of the first record specified in the fetch result. The default is the first field.
PDOStatement::fetch() is used to obtain a record,
PDOStatement::fetchAll() is used to obtain all record sets into one. To obtain the results, you can set the type of the required result set through PDOStatement::setFetchMode.

There are two other peripheral operations, one is PDO::lastInsertId() and PDOStatement::rowCount(). PDO::lastInsertId() returns the last insertion operation, and the primary key column type is the last auto-increment ID.
PDOStatement::rowCount() is mainly used for the result set affected by PDO::query() and PDO::prepare()'s Delete, Insert, and Update operations. It is invalid for the PDO::exec() method and Select operation. .

Related recommendations:

The reason why connecting mysql through PDO can prevent injection

ThinkPHP framework based on PDO method to connect database operation example

Example of PDO transaction processing operation in PHP

The above is the detailed content of Detailed explanation of PDO class in PHP5. 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

Video Face Swap

Video Face Swap

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

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

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

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

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