PHP PDO函数库详解
PDO是一个“数据库访问抽象层”,作用是统一各种数据库的访问接口,与mysql和mysqli的函数库相比,PDO让跨数据库的使用更具有亲和力;与ADODB和MDB2相比,PDO更高效。
目前而言,实现“数据库抽象层”任重而道远,使用PDO这样的“数据库访问抽象层”是一个不错的选择。
PDO中包含三个预定义的类
PDO中包含三个预定义的类,它们分别是 PDO、PDOStatement 和 PDOException。
一、PDO
PDO-> — 标明回滚起始点
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-> — 标明回滚起始点
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->,PDO->commit(),PDO->rollBack()这三个方法是在支持回滚功能时一起使用的。PDO->方法标明起始点,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->;
$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-> 方法创建一个。如果底层驱动不支持事务处理,一个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代号,特定数据库驱动的错误代号和特定数据库驱动的错误字符串。
属性列表:

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

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

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

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,

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

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.
