Detailed explanation of PDO examples in PHP
1. 何为PDO?
PDO(PHP数据对象) 是一个轻量级的、具有兼容接口的PHP数据连接拓展,是一个PHP官方的PECL库,随PHP 5.1发布,需要PHP 5的面向对象支持,因而在更早的版本上无法使用。它所提供的数据接入抽象层,具有与具体数据库类型无关的优势,为它所支持的数据库提供统一的操作接口。目前支持的数据库有Cubrid、FreeTDS / Microsoft SQL Server / Sybase、Firebird/Interbase 6、IBM DB2、IBM Informix Dynamic Server、MySQL 3.x/4.x/5.x、Oracle Call Interface、ODBC v3 (IBM DB2, unixODBC and win32 ODBC)、PostgreSQL、SQLite 3 and SQLite 2、Microsoft SQL Server / SQL Azure等。由于PDO是在底层实现的统一的数据库操作接口,因而利用它能够实现更高级的数据库操作,比如存储过程的调度等。
2. PDO实例
下面将实现一个用PDO连接SQLite数据库的实现分页显示的例子,查询的结果输出为JSON数据。
<?php $cat = isset ($_GET['cat']) ? $_GET['cat'] : "1"; $pg = isset ($_GET['pg']) ? $_GET['pg'] : "1"; $limit = 10; $dbname = 'shelf.sqlite'; try { $db = new PDO("sqlite:" . $dbname); $sth = $db->prepare('select * from book where cat_id=:id limit :offset, :limit', array ( PDO :: ATTR_CURSOR => PDO :: CURSOR_FWDONLY )); $result = $sth->execute(array ( ':id' => $cat, ':offset' => ($pg -1) * $limit, ':limit' => $limit )); $list = array (); $query = $db->query('select count(*) from book where cat_id=' . $cat)->fetch(); //Only 1 row $list["count"] = $query[0]; if ($result) { while ($row = $sth->fetch(PDO :: FETCH_ASSOC)) { $list["books"][] = $row; } } else { print_r($db->errorInfo()); } $db = NULL; echo str_replace('\\/', '/', json_encode($list)); } catch (PDOException $ex) { print_r($ex); } ?>
3. PDO中的常量
PDO库中定义了一些静态常量,这些常量用PDO ::
$query=$db->prepare('select * from book where cat_id=:id limit :offset, :limit', array ( PDO :: ATTR_CURSOR => PDO :: CURSOR_FWDONLY ));
这里的PDO :: ATTR_CURSOR和PDO :: CURSOR_FWDONLY都是PDO常量,这里将数据库的cursor类型设为forward only。
4. PDO中的连接和连接管理
PDO中的连接是通过创建PDO类的实例而建立的。创造时需要提供数据源名称(DSN)及可选的用户名和密码等参数。在这个过程中值得注意的是,如果发生异常,PHP的Zend引擎默认操作是将具体的错误信息显示出来,这就带来一个问题:连接信息(数据位置、用户名、密码等)可能遭到泄露。因此,为严防此类不幸的事情发生,一定要显式捕获异常,无论是用try...catch语句还是用set_exception_handler()函数,隐藏一些敏感数据。所不同的是,调用set_exception_handler()后代码的执行将终止,而采用try...catch的形式,异常之后的代码将继续执行,正如try...catch语句的原意一般(更多请移步:PHP学习笔记之异常捕获与处理)。
<?php $db = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //使用新建立的数据库连接。 //... ... //连接在PDO实例的生命周期里是活动的。使用完毕后应当关闭此连接,若不这样做PHP在代码结束时才关闭此连接,将占用一部分内存。 $db = null; ?>
当然,事情并不都是这样,有时我们可能会需要一个永久的连接。具体做法是在PDO的构造函数里再加一个参数:
<?php $db = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array( PDO::ATTR_PERSISTENT => true )); ?>
永久的连接能够跨越代码,在一个代码执行完毕时并未被关闭,而是被缓存起来,以供另一段拥有同样权限的代码重复使用。这样便不必每次都新建一个连接,省了不少事不说,还能够加快网站速度。
5. PDO中的查询操作:exec/query/prepared statement
在PDO中有三种方法执行查询操作,分别是用exec、query和使用prepared statement。三种方法各有利弊,先说exec。
(1)PDO::exec()一般用于执行一次的SQL语句,返回受查询影响的行数。它不适用于SELECT语句,如果需要用一次是SELECT语句,可以用PDO::query();也不适用于多次使用的语句,如果有多次使用的需求,考虑用PDO::prepare()。
(2)PDO::query()用于执行一次SELECT语句,执行后应当随即使用PDOStatement::fetch()语句将结果取出,否则立即进行下一次的PDO::query()将会报错。在2.PDO实例部分,为了得到查询数据的总量,就用了PDO::query()语句。
(3)PDOStatement表示一个prepared statement语句,而在执行之后,又将返回一组关联数组的结果。如果一类查询(查询结构相似而具体的参数不一)需要一次解析而执行使用很多次,可以先用prepared statement,这样可以为具体的查询的执行做好准备,避免了分析、编译、优化的循环,将减少资源占用率,从而提高运行效率。通过对数据库进行prepare操作,便会返回PDOStatement数据类型,从而在其基础上展开execute、fetch等进一步的操作。
$sth = $db->prepare('select * from book where cat_id=:id limit :offset, :limit', array ( PDO :: ATTR_CURSOR => PDO :: CURSOR_FWDONLY )); //用$limit1得到一个结果 $result1 = $sth->execute(array ( ':id' => $cat, ':offset' => ($pg -1) * $limit1, ':limit' => $limit1 )); //用$limit2得到另一个结果 $result2 = $sth->execute(array ( ':id' => $cat, ':offset' => ($pg -1) * $limit2, ':limit' => $limit2 ));
使用prepared statement还有一个好处就是,语句里不再使用引号,PDO driver已自动完成这一操作,可以防止SQL注入攻击的危险。查询语句里可以使用包含名字的(:name)和问号(?)的参数占位符,分别将用associated array 和indexed array传入数值。
//用位置参入参数 $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $value); //用名称传入参数 $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); $name = 'one'; $value = 1; $stmt->execute(); ///////////////////////////////////////////// //也可以这样实现 //用位置参入参数,indexed array $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)"); $name = 'one'; $value = 1; $stmt->execute(array($name,$value)); //用名称传入参数, associated array $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); $name = 'one'; $value = 1; $stmt->execute(array(':name'=>$name,':value'=>$value));
特别注意:查询语句中的占位符应当是占据整个值的位置,如果有模糊查询的符号,应当这样做:
// placeholder must be used in the place of the whole value $stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?"); $stmt->execute(array("%$_GET[name]%")); //下面这样就有问题了 $stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'"); $stmt->execute(array($_GET['name']));
相关推荐:
The above is the detailed content of Detailed explanation of PDO examples in PHP. For more information, please follow other related articles on the PHP Chinese website!

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