PHP 中使用 PDO
PDO简介
PDO 是一个“数据库访问抽象层”,作用是统一各种数据库(MySQL、MSSQL、Oracle、DB2、PostgreSQL……)的访问接口,能轻松的在不同的数据库之间完成切换,使得数据库间的移植容易实现。
PDO 驱动
支持PDO 的驱动及相应的数据库列表 | |
驱动名 | 对应访问的数据库 |
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase |
PDO_FIREBIRD | Firebird / Interbase 6 |
PDO_MYSQL | MySQL |
PDO_OCI | Oracle |
PDO_ODBC | ODBC v3 |
PDO_PGSQL | PostgreSQL |
PDO_SQLITE | SQLite |
PDO安装
PDO 是 PHP 5.1 发行的,也就是说,在 5.1 之前的版本是不支持 PDO 的,PDO 也是未来 PHP 处理数据库的首选和趋势。
下面介绍 PDO 的安装:
1、Linux 环境
在 Linux 环境中下为启用对 MySQL 的 PDO 程序驱动支持,需要在安装 PHP (5.1以上版本)的源代码包时,向 configure 命令中添加:
--with-pdo-mysql=/usr/local/mysql // "/usr/local/mysql"为 MySQL 服务器的安装目录
--with-pdo-mysql=/usr/local/mysql // "/usr/local/mysql"为 MySQL 服务器的安装目录
2、Windows 环境
修改 php.ini 文件,找到如下,把前面的“;”(分号:代表注释)去掉即可!
;extension=php_pdo.dll // 所有 PDO 驱动共享的扩展,这个必须有
;extension=php_pdo_mysql.dll // 使用 MySQL 使用这行
;extension=php_pdo_mssql.dll // 使用 MSSQL 使用这行
;extension=php_pdo.dll // 所有 PDO 驱动共享的扩展,这个必须有
;extension=php_pdo_mysql.dll // 使用 MySQL 使用这行
;extension=php_pdo_mssql.dll // 使用 MSSQL 使用这行
保存 php.ini 文件,重启 Apache 服务器,查看 phpinfo() 函数,出现下图说明安装成功。
注意:Windows 环境中,有时可能配置不成功,出现不了上图的现象。这时,把 PHP 安装扩展中的 php_pdo_mysql.dll、php_pdo.dll……等文件拷贝到系统安装路径的 Windows 下。
创建 PDO 对象
PDO 的构造方法原型如下:
__construct(string dsn [,string db_user [,string db_pwd [,array driver_options]]])
__construct(string dsn [,string db_user [,string db_pwd [,array driver_options]]])参数说明:
1、dsn(data source name):数据源名称,定义用到的数据库和驱动;
a、连接 MySQL 数据库的DSN:mysql:host=localhost;dbname=test // 主机名为:localhost;数据库名称为:test
b、连接 Oracle 数据库的DSN:oci:dbname=//localhost:1521/test // 主机名为:localhost;端口:1521;数据库名称为:test
……更多的 DSN 请参考 PHP 手册
2、db_user:数据库用户名;
3、db_pwd:数据库密码;
4、driver_options:是一个数组,用来指定连接所需的所有额外选项
PDO 用来指定连接所需的所有额外选项
选项名 | 描述 |
PDO::ATTR_AUTOCOMMIT | 确定PDO 是否关闭自动提交功能,设置FALSE 为关闭 |
PDO::ATTR_CASE | 强制PDO 获取的表字段字符的大小写转换,或原样使用列信息 |
PDO::ATTR_ERRMODE | 设置错误处理的模式 |
PDO::ATTR_PERSISTENT | 确定连接是否为持久连接,默认为FALSE,不持久连接 |
PDO::ATTR_ORACLE_NULLS | 将返回的空字符串转换为SQL 的NULL |
PDO::ATTR_PREFETCH | 设置应用程序提前获取的数据大小,以K 字节为单位 |
PDO::ATTR_TIMEOUT | 设置超时之前的等待时间(秒为单位) |
PDO::ATTR_SERVER_INFO | 包含与数据库特有的服务器信息 |
PDO::ATTR_SERVER_VERSION | 包含与数据库服务器版本号有关的信息 |
PDO::ATTR_CLIENT_VERSION | 包含与数据库客户端版本号有关的信息 |
PDO::ATTR_CONNECTION_STATUS | 设置超时之前的等待时间(秒为单位) |
调用 PDO 构造方法(连接数据库)
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544', array(PDO::ATTR_PERSISTENT=>true));
} catch (PDOException $e) {
exit('数据库连接失败,错误信息:'. $e->getMessage());
}
?>
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544', array(PDO::ATTR_PERSISTENT=>true));
} catch (PDOException $e) {
exit('数据库连接失败,错误信息:'. $e->getMessage());
}
?>
PDO 对象的成员方法
PDO对象中的成员方法
方法名 | 描述 |
getAttribute() | 获取一个“数据库连接对象”的属性 |
setAttribute() | 为一个“数据库连接对象”设定属性 |
errorCode() | 获取错误码 |
errorInfo() | 获取错误信息 |
exec() | 处理一条SQL 语句,并返回所影响的行数 |
query() | 处理一条SQL 语句,并返回一个"PDOStatement" 对象 |
quote() | 为某个SQL 中的字符串添加引号 |
lastInsertId() | 获取插入到表中的最后一条数据的主键值 |
prepare() | 负责准备执行的SQL 语句 |
getAvailableDrivers() | 获取有效的PDO 驱动器名称 |
beginTransaction() | 开始一个事务,标明回滚起始点 |
commit() | 提交一个事务,并执行SQL |
rollback() | 回滚一个事务 |
使用 PDO 执行 SQL 语句
1、使用 PDO::exec() 方法
PDO::exec() 方法多用在 SQL 中的 INSERT、UPDATE、DELETE,返回的为受影响的行数
date_default_timezone_set('PRC');
header('Content-Type:text/html;Charset=utf-8');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544');
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
$pdo->query('SET NAMES utf8'); // 设置数据库编码
} catch (PDOException $e) {
exit('数据库连接错误,错误信息:'. $e->getMessage());
}
$addTime = date('Y-m-d H:i:s', time());
$sql = "INSERT INTO think_user(userName,email,age,addTime) VALUES ('酒井法子','jiujinfazi@sina.com.cn','28','{$addTime}')";
$row = $pdo->exec($sql);
if ($row) {
echo '添加成功';
} else {
echo '添加失败';
}
?>
date_default_timezone_set('PRC');
header('Content-Type:text/html;Charset=utf-8');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544');
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
$pdo->query('SET NAMES utf8'); // 设置数据库编码
} catch (PDOException $e) {
exit('数据库连接错误,错误信息:'. $e->getMessage());
}
$addTime = date('Y-m-d H:i:s', time());
$sql = "INSERT INTO think_user(userName,email,age,addTime) VALUES ('酒井法子','jiujinfazi@sina.com.cn','28','{$addTime}')";
$row = $pdo->exec($sql);
if ($row) {
echo '添加成功';
} else {
echo '添加失败';
}
?>
2、使用 PDO::query() 方法
PDO::query() 方法用在 SQL 中的 SELECT 查询上。如果该方法执行成功,那么将返回一个 PDOStatement 对象,使用 rowCount() 方法可以返回影响的行数
header('Content-Type:text/html;Charset=utf-8');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544');
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
$pdo->query('SET NAMES utf8'); // 设置数据库编码
} catch (PDOException $e) {
exit('数据库连接错误,错误信息:'. $e->getMessage());
}
$sql = "SELECT userName,email,age,addTime FROM think_user";
try {
$result = $pdo->query($sql);
foreach ($result as $row) {
echo $row['userName'] . "\t" . $row['email'] . "\t" .$row['age'] . "\t" .$row['addTime'] . '
';
}
echo '总共'. $result->rowCount() .'条';
} catch (PDOException $e) {
exit($e->getMessage());
}
?>
header('Content-Type:text/html;Charset=utf-8');
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '1715544');
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL
$pdo->query('SET NAMES utf8'); // 设置数据库编码
} catch (PDOException $e) {
exit('数据库连接错误,错误信息:'. $e->getMessage());
}
$sql = "SELECT userName,email,age,addTime FROM think_user";
try {
$result = $pdo->query($sql);
foreach ($result as $row) {
echo $row['userName'] . "\t" . $row['email'] . "\t" .$row['age'] . "\t" .$row['addTime'] . '
';
}
echo '总共'. $result->rowCount() .'条';
} catch (PDOException $e) {
exit($e->getMessage());
}
?>
PDO 对预处理语句的支持
摘自 Lee.的专栏

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

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...
