Home Backend Development PHP Tutorial Detailed explanation of PHP PDO function library_PHP tutorial

Detailed explanation of PHP PDO function library_PHP tutorial

Jul 21, 2016 pm 03:38 PM
pdo php use function accomplish Library abstract database yes of at present access Detailed explanation

目前而言,实现“数据库抽象层”任重而道远,使用PDO这样的“数据库访问抽象层”是一个不错的选择。

PDO中包含三个预定义的类

PDO中包含三个预定义的类,它们分别是 PDO、PDOStatement 和 PDOException。

一、PDO

PDO->beginTransaction() — 标明回滚起始点
PDO->commit() — 标明回滚结束点,并执行SQL
PDO->__construct() — 建立一个PDO链接数据库的实例
PDO->errorCode() — 获取错误码
PDO->errorInfo() — 获取错误的信息
PDO->exec() — 处理一条SQL语句,并返回所影响的条目数
PDO->getAttribute() — 获取一个“数据库连接对象”的属性
PDO->getAvailableDrivers() — 获取有效的PDO驱动器名称
PDO->lastInsertId() — 获取写入的最后一条数据的主键值
PDO->prepare() — 生成一个“查询对象”
PDO->query() — 处理一条SQL语句,并返回一个“PDOStatement”
PDO->quote() — 为某个SQL中的字符串添加引号
PDO->rollBack() — 执行回滚
PDO->setAttribute() — 为一个“数据库连接对象”设定属性

二、PDOStatement

PDOStatement->bindColumn() — Bind a column to a PHP variable
PDOStatement->bindParam() — Binds a parameter to the specified variable name
PDOStatement->bindValue() — Binds a value to a parameter
PDOStatement->closeCursor() — Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() — Returns the number of columns in the result set
PDOStatement->errorCode() — Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() — Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() — Executes a prepared statement
PDOStatement->fetch() — Fetches the next row from a result set
PDOStatement->fetchAll() — Returns an array containing all of the result set rows
PDOStatement->fetchColumn() — Returns a single column from the next row of a result set
PDOStatement->fetchObject() — Fetches the next row and returns it as an object.
PDOStatement->getAttribute() — Retrieve a statement attribute
PDOStatement->getColumnMeta() — Returns metadata for a column in a result set
PDOStatement->nextRowset() — Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() — Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() — Set a statement attribute
PDOStatement->setFetchMode() — Set the default fetch mode for this statement

PDO是一个“数据库访问抽象层”,作用是统一各种数据库的访问接口,与mysql和mysqli的函数库相比,PDO让跨数据库的使用更具有亲和力;与ADODB和MDB2相比,PDO更高效。目前而言,实现“数据库抽象层”任重而道远,使用PDO这样的“数据库访问抽象层”是一个不错的选择。

PDO中包含三个预定义的类

PDO中包含三个预定义的类,它们分别是 PDO、PDOStatement 和 PDOException。

一、PDO

PDO->beginTransaction() — 标明回滚起始点
PDO->commit() — 标明回滚结束点,并执行SQL
PDO->rollBack() — 执行回滚
PDO->__construct() — 建立一个PDO链接数据库的实例
PDO->errorCode() — 获取错误码
PDO->errorInfo() — 获取错误的信息
PDO->exec() — 处理一条SQL语句,并返回所影响的条目数
PDO->getAttribute() — 获取一个“数据库连接对象”的属性
PDO->getAvailableDrivers() — 获取有效的PDO驱动器名称
PDO->lastInsertId() — 获取写入的最后一条数据的主键值
PDO->prepare() — 生成一个“查询对象”
PDO->query() — 处理一条SQL语句,并返回一个“PDOStatement”
PDO->quote() — 为某个SQL中的字符串添加引号
PDO->setAttribute() — 为一个“数据库连接对象”设定属性

详解1) PDO中的数据库连接
$dsn = ‘mysql:dbname=ent;host=127.0.0.1′;
$user = ‘root';
$password = ‘123456′;
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true));
$dbh->query('set names utf8;');
foreach ($dbh->query('SELECT * from tpm_juese') as $row) {
print_r($row);
}
} catch (PDOException $e) {
echo ‘Connection failed: ‘ . $e->getMessage();
}

许多Web应用会因为使用了向数据库的持久连接而得到优化。持久连接不会在脚本结束时关闭,
相反它会被缓存起来并在另一个脚本通过同样的标识请求一个连接时得以重新利用。
持久连接的缓存可以使你避免在脚本每次需要与数据库对话时都要部署一个新的连接的资源消耗,让你的Web应用更加快速。
上面实例中的array(PDO::ATTR_PERSISTENT => true)就是把连接类型设置为持久连接。

详解2) PDO中的事务
PDO->beginTransaction(),PDO->commit(),PDO->rollBack()这三个方法是在支持回滚功能时一起使用的。PDO->beginTransaction()方法标明起始点,PDO->commit()方法标明回滚结束点,并执行SQL,PDO->rollBack()执行回滚。
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', ‘root', ”);
$dbh->query('set names utf8;');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->beginTransaction();
$dbh->exec(”INSERT INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);”);
$dbh->exec(”INSERT INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);”);
$dbh->exec(”INSERT INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);”);
$dbh->commit();

} catch (Exception $e) {
$dbh->rollBack();
echo “Failed: ” . $e->getMessage();
}
?>
现在你已经通过PDO建立了连接,在部署查询之前你必须搞明白PDO是怎样管理事务的。如果你以前从未遇到过事务处理,(现在简单介绍一下:)它们提供了4个主要的特性:原子性,一致性,独立性和持久性(Atomicity, Consistency, Isolation and Durability,ACID)通俗一点讲,一个事务中所有的工作在提交时,即使它是分阶段执行的,也要保证安全地应用于数据库,不被其他的连接干扰。事务工作也可以在请求发生错误时轻松地自动取消。

事务的典型运用就是通过把批量的改变“保存起来”然后立即执行。这样就会有彻底地提高更新效率的好处。换句话说,事务可以使你的脚本更快速同时可能更健壮(要实现这个优点你仍然需要正确的使用它们)。

不幸运的是,并不是每个数据库都支持事务,因此PDO需要在建立连接时运行在被认为是“自动提交”的模式下。自动提交模式意味着你执行的每个查询都有它自己隐含的事务处理,无论数据库支持事务还是因数据库不支持而不存在事务。如果你需要一个事务,你必须使用 PDO->beginTransaction() 方法创建一个。如果底层驱动不支持事务处理,一个PDOException就会被抛出(与你的异常处理设置无关,因为这总是一个严重的错误状态)。在一个事物中,你可以使用 PDO->commit() 或 PDO->rollBack() 结束它,这取决于事务中代码运行是否成功。

当脚本结束时或一个连接要关闭时,如果你还有一个未处理完的事务,PDO将会自动将其回滚。这是对于脚本意外终止的情况来说是一个安全的方案——如果你没有明确地提交事务,它将会假设发生了一些错误,为了你数据的安全,所以就执行回滚了。

二、PDOStatement

PDOStatement->bindColumn() — Bind a column to a PHP variable
PDOStatement->bindParam() — Binds a parameter to the specified variable name
PDOStatement->bindValue() — Binds a value to a parameter
PDOStatement->closeCursor() — Closes the cursor, enabling the statement to be executed again.
PDOStatement->columnCount() — Returns the number of columns in the result set
PDOStatement->errorCode() — Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement->errorInfo() — Fetch extended error information associated with the last operation on the statement handle
PDOStatement->execute() — Executes a prepared statement
PDOStatement->fetch() — Fetches the next row from a result set
PDOStatement->fetchAll() — Returns an array containing all of the result set rows
PDOStatement->fetchColumn() — Returns a single column from the next row of a result set
PDOStatement->fetchObject() — Fetches the next row and returns it as an object.
PDOStatement->getAttribute() — Retrieve a statement attribute
PDOStatement->getColumnMeta() — Returns metadata for a column in a result set
PDOStatement->nextRowset() — Advances to the next rowset in a multi-rowset statement handle
PDOStatement->rowCount() — Returns the number of rows affected by the last SQL statement
PDOStatement->setAttribute() — Set a statement attribute
PDOStatement->setFetchMode() — Set the default fetch mode for this statement

三、PDOException

PDO 提供了3中不同的错误处理策略。
1. PDO::ERRMODE_SILENT
这是默认使用的模式。PDO会在statement和database对象上设定简单的错误代号,你可以使用PDO->errorCode() 和 PDO->errorInfo() 方法检查错误;如果错误是在对statement对象进行调用时导致的,你就可以在那个对象上使用 PDOStatement->errorCode() 或 PDOStatement->errorInfo() 方法取得错误信息。而如果错误是在对database对象调用时导致的,你就应该在这个database对象上调用那两个方法。
2. PDO::ERRMODE_WARNING
作为设置错误代号的附加,PDO将会发出一个传统的E_WARNING信息。这种设置在除错和调试时是很有用的,如果你只是想看看发生了什么问题而不想中断程序的流程的话。
3. PDO::ERRMODE_EXCEPTION
作为设置错误代号的附件,PDO会抛出一个PDOException异常并设置它的属性来反映错误代号和错误信息。这中设置在除错时也是很有用的,因为他会有效的“放大(blow up)”脚本中的出错点,非常快速的指向一个你代码中可能出错区域。(记住:如果异常导致脚本中断,事务处理回自动回滚。)
异常模式也是非常有用的,因为你可以使用比以前那种使用传统的PHP风格的错误处理结构更清晰的结构处理错误,比使用安静模式使用更少的代码及嵌套,也能够更加明确地检查每个数据库访问的返回值。
关于PHP中异常的更多信息请看Exceptions章节
PDO 使用基于SQL-92 SQLSTATE 的错误代号字符串;特定的PDO驱动应当将自己本身的代号对应到适当的SQLSTATE代号上。PDO->errorCode() 方法只返回单一的SQLSTATE代号。如果你需要关于一个错误的更加有针对性的信息,PDO也提供了一个PDO->errorInfo()方法,它可以返回一个包含了SQLSTATE代号,特定数据库驱动的错误代号和特定数据库驱动的错误说明字符串。


// 修改默认的错误显示级别
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
?>

属性列表:

PDO::PARAM_BOOL
表示一个布尔类型
PDO::PARAM_NULL
表示一个
SQL中的NULL类型
PDO::PARAM_INT
表示一个
SQL中的INTEGER类型
PDO::PARAM_STR
表示一个
SQL中的SQL CHARVARCHAR类型
PDO::PARAM_LOB
表示一个
SQL中的large object类型
PDO::PARAM_STMT
表示一个
SQL中的recordset类型,还没有被支持
PDO::PARAM_INPUT_OUTPUT
Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.
PDO::FETCH_LAZY
将每一行结果作为一个对象返回
PDO::FETCH_ASSOC
仅仅返回以键值作为下标的查询的结果集,名称相同的数据只返回一个
PDO::FETCH_NAMED
仅仅返回以键值作为下标的查询的结果集,名称相同的数据以数组形式返回
PDO::FETCH_NUM
仅仅返回以数字作为下标的查询的结果集
PDO::FETCH_BOTH
同时返回以键值和数字作为下标的查询的结果集
PDO::FETCH_OBJ
以对象的形式返回结果集
PDO::FETCH_BOUND
PDOStatement::bindParam()PDOStatement::bindColumn()所绑定的值作为变量名赋值后返回
PDO::FETCH_COLUMN
表示仅仅返回结果集中的某一列
PDO::FETCH_CLASS
表示以类的形式返回结果集
PDO::FETCH_INTO
表示将数据合并入一个存在的类中进行返回
PDO::FETCH_FUNC
PDO::FETCH_GROUP
PDO::FETCH_UNIQUE
PDO::FETCH_KEY_PAIR
以首个键值下表,后面数字下表的形式返回结果集
PDO::FETCH_CLASSTYPE
PDO::FETCH_SERIALIZE
表示将数据合并入一个存在的类中并序列化返回
PDO::FETCH_PROPS_LATE
Available since PHP 5.2.0
PDO::ATTR_AUTOCOMMIT
在设置成
true的时候,PDO会自动尝试停止接受委托,开始执行
PDO::ATTR_PREFETCH
设置应用程序提前获取的数据大小,并非所有的数据库哦度支持
PDO::ATTR_TIMEOUT
设置连接数据库超时的值
PDO::ATTR_ERRMODE
设置
Error处理的模式
PDO::ATTR_SERVER_VERSION
只读属性,表示
PDO连接的服务器端数据库版本
PDO::ATTR_CLIENT_VERSION
只读属性,表示
PDO连接的客户端PDO驱动版本
PDO::ATTR_SERVER_INFO
Read-only attribute, indicating
PDOmeta information of the connected server
PDO::ATTR_CONNECTION_STATUS
PDO::ATTR_CASE
Operate the contents of
PDO::CASE_* in the form of columns
PDO ::ATTR_CURSOR_NAME
Get or set the name of the pointer
PDO::ATTR_CURSOR
sets the type of pointer,
PDO now supports PDO:: CURSOR_FWDONLY and PDO::CURSOR_FWDONLY
PDO::ATTR_DRIVER_NAME
Returns the name of the used
PDO driver
PDO::ATTR_ORACLE_NULLS
Convert the returned empty string to
SQL NULL
PDO::ATTR_PERSISTENT
Gets a Existing connection
PDO::ATTR_STATEMENT_CLASS
PDO ::ATTR_FETCH_CATALOG_NAMES
Use custom catalog names in place of field names in the returned result set.
PDO::ATTR_FETCH_TABLE_NAMES
Use custom table names in place of field names in the returned result set.
PDO::ATTR_STRINGIFY_FETCHES
PDO::ATTR_MAX_COLUMN_LEN
PDO::ATTR_DEFAULT_FETCH_MODE
Available since PHP 5.2.0
PDO::ATTR_EMULATE_PREPARES
Available since PHP 5.1.3.
PDO::ERRMODE_SILENT
发生错误时不汇报任何的错误信息,是默认值
PDO::ERRMODE_WARNING
发生错误时发出一条
phpE_WARNING的信息
PDO::ERRMODE_EXCEPTION
发生错误时抛出一个
PDOException
PDO::CASE_NATURAL
回复列的默认显示格式
PDO::CASE_LOWER
强制列的名字小写
PDO::CASE_UPPER
强制列的名字大写
PDO::NULL_NATURAL
PDO::NULL_EMPTY_STRING
PDO::NULL_TO_STRING
PDO::FETCH_ORI_NEXT
获取结果集中的下一行数据,仅在有指针功能时有效
PDO::FETCH_ORI_PRIOR
获取结果集中的上一行数据,仅在有指针功能时有效
PDO::FETCH_ORI_FIRST
获取结果集中的第一行数据,仅在有指针功能时有效
PDO::FETCH_ORI_LAST
获取结果集中的最后一行数据,仅在有指针功能时有效
PDO::FETCH_ORI_ABS
获取结果集中的某一行数据,仅在有指针功能时有效
PDO::FETCH_ORI_REL
获取结果集中当前行后某行的数据,仅在有指针功能时有效
PDO::CURSOR_FWDONLY
建立一个只能向后的指针操作对象
PDO::CURSOR_SCROLL
建立一个指针操作对象,传递
PDO::FETCH_ORI_*中的内容来控制结果集
PDO::ERR_NONE (string)
设定没有错误时候的错误信息
PDO::PARAM_EVT_ALLOC
Allocation event
PDO::PARAM_EVT_FREE
Deallocation event
PDO::PARAM_EVT_EXEC_PRE
Event triggered prior to execution of a prepared statement.
PDO::PARAM_EVT_EXEC_POST
Event triggered subsequent to execution of a prepared statement.
PDO::PARAM_EVT_FETCH_PRE
Event triggered prior to fetching a result from a resultset.
PDO::PARAM_EVT_FETCH_POST
Event triggered subsequent to fetching a result from a resultset.
PDO::PARAM_EVT_NORMALIZE
Event triggered during bound parameter registration allowing the driver to normalize the parameter name.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321689.htmlTechArticleCurrently, there is a long way to go to implement the "database abstraction layer". Using "database access abstraction" such as PDO Layers" is a good choice. PDO contains three predefined classes. PDO contains...
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

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