php pdo:php pdo 学习笔记
■pdo为何物?pod(php data object)扩展在php5中加入,php6中将默认识用pdo连接数据库,所有非pdo扩展将会在php6被从扩展中移除。该扩展提供php内置类 pdo来对数据库进行访问,不同数据库使用相同的方法名,解决数据库连接不统一的问题。我是配置在windows下做开发用的。■pdo的目标
提供一种轻型、清晰、方便的 api
统一各种不同 rdbms 库的共有特性,但不排除更高级的特性。
通过 php 脚本提供可选的较大程度的抽象/兼容性。
■pdo的特点:
性能。pdo 从一开始就吸取了现有数据库扩展成功和失败的经验教训。因为 pdo 的代码是全新的,所以我们有机会重新开始设计性能,以利用 php 5 的最新特性。
能力。pdo 旨在将常见的数据库功能作为基础提供,同时提供对于 rdbms 独特功能的方便访问。
简单。pdo 旨在使您能够轻松使用数据库。api 不会强行介入您的代码,同时会清楚地表明每个函数调用的过程。
运行时可扩展。pdo 扩展是模块化的,使您能够在运行时为您的数据库后端加载驱动程序,而不必重新编译或重新安装整个 php 程序。例如,pdo_oci 扩展会替代 pdo 扩展实现 oracle 数据库 api。还有一些用于 mysql、postgresql、odbc 和 firebird 的驱动程序,更多的驱动程序尚在开发。
■安装pdo
我这里是windows下开发用的pdo扩展,要是你要在linux下安装配置,请到别的地方寻找。
版本要求:php5.1以及以后版本的程序包里已经带了;php5.0.x则要到pecl.php.net下载,放到你的扩展库,就是php所在的文件夹的ext文件夹下;手册上说5.0之前的版本不能运行pdo扩展。配置:
修改你的php.ini配置文件,使它支持pdo.(php.ini这个东西没有弄懂的话,先弄清楚,要修改调用你的phpinfo()函数所显示的那个php.ini)把extension=php_pdo.dll前面的分号去掉,分毫是php配置文件注释符号,这个扩展是必须的。往下还有
;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各各扩展所对应的数据库是:
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 |
■使用pdo
我这里假设你已经装好mysql了,要是没装的话,麻烦先想办法装上,我的是mysql5.0.22,黑夜路人用的是mysql 4.0.26也可以用。★数据库的连接:
我们通过下面的例子来分析pdo连接数据库,
$dbms='mysql'; //数据库类型 oracle 用odi,对于开发者来说,使用不同的数据库,只要改这个,不用记住那么多的函数了 $host='localhost'; //数据库主机名 $dbname='test'; //使用的数据库 $user='root'; //数据库连接用户名 $pass=''; //对应的密码 $dsn="$dbms:host=$host;dbname=$dbname"; // try { $dbh = new pdo($dsn, $user, $pass); //初始化一个pdo对象,就是创建了数据库连接对象$dbh echo "连接成功 "; /*你还可以进行一次搜索操作 foreach ($dbh->query('select * from foo') as $row) { print_r($row); //你可以用 echo($global); 来看到这些值 } */ $dbh = null; } catch (pdoexception $e) { die ("error!: " . $e->getmessage() . " "); } //默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(pdo::attr_persistent => true) 变成这样: $db = new pdo($dsn, $user, $pass, array(pdo::attr_persistent => true)); ?> |
★数据库查询:
上面我们已经进行了一次查询,我们还可以使用如下的查询:
$db->setattribute(pdo::attr_case, pdo::case_upper); //设置属性 $rs = $db->query("select * from foo"); $rs->setfetchmode(pdo::fetch_assoc); $result_arr = $rs->fetchall(); print_r($result_arr); ?> |
以上因为用到setattribute()方法,放上那两个参数,把字段名强制转换成大写。下面列出多有pdo::setattribute()的参数: pdo::attr_case: 强制列名变成一种格式,详细如下(第二个参数):
pdo::case_lower: 强制列名是小写.
pdo::case_natural: 列名按照原始的方式
pdo::case_upper: 强制列名为大写.
pdo::attr_errmode: 错误提示.
pdo::errmode_silent: 不显示错误信息,只显示错误码.
pdo::errmode_warning: 显示警告错误.
pdo::errmode_exception: 抛出异常.
pdo::attr_oracle_nulls (不仅仅是oracle有效,别的数据库也有效): )指定数据库返回的null值在php中对应的数值。
pdo::null_natural: 不变.
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);是pdostatement::setfetchmode(),对返回类型的声明。
有如下:
pdo::fetch_assoc -- 关联数组形式
pdo::fetch_num -- 数字索引数组形式
pdo::fetch_both -- 两者数组形式都有,这是缺省的
pdo::fetch_obj -- 按照对象的形式,类似于以前的 mysql_fetch_object()
更多返回类型声明(pdostatement::方法名)看手册。
★插入,更新,删除数据,
$db->exec("delete from `xxxx_menu` where mid=43"); |
简单的总结一下上面的操作:
查询操作主要是pdo::query()、pdo::exec()、pdo::prepare()。
pdo::query()主要是用于有记录结果返回的操作,特别是select操作,
pdo::exec()主要是针对没有结果集合返回的操作,比如insert、update、delete等操作,它返回的结果是当前操作影响的列数。
pdo::prepare()主要是预处理操作,需要通过$rs->execute()来执行预处理里面的sql语句,这个方法可以绑定参数,功能比较强大,不是本文能够简单说明白的,大家可以参考手册和其他文档。
获取结果集操作主要是:pdostatement::fetchcolumn()、pdostatement::fetch()、pdostatement::fetchall()。
pdostatement::fetchcolumn() 是获取结果指定第一条记录的某个字段,缺省是第一个字段。
pdostatement::fetch() 是用来获取一条记录,
pdostatement::fetchall()是获取所有记录集到一个中,获取结果可以通过pdostatement::setfetchmode来设置需要结果集合的类型。
另外有两个周边的操作,一个是pdo::lastinsertid()和pdostatement::rowcount()。pdo::lastinsertid()是返回上次插入操作,主键列类型是自增的最后的自增id。
pdostatement::rowcount()主要是用于pdo::query()和pdo::prepare()进行delete、insert、update操作影响的结果集,对pdo::exec()方法和select操作无效。
★事务和自动提交
至此,您已经通过 pdo 连接到了 mysql,在发出查询之前,您应该理解 pdo 是如何管理事务的。如果之前没有接触过事务,那么首先要知道事务的 4 个特征:原子性(atomicity)、一致性(consistency)、独立性(isolation)和持久性(durability),即 acid。用外行人的话说,对于在一个事务中执行的任何工作,即使它是分阶段执行的,也一定可以保证该工作会安全地应用于数据库,并且在工作被提交时,不会受到来自其他连接的影响。事务性工作可以根据请求自动撤销(假设您还没有提交它),这使得脚本中的错误处理变得更加容易。
事务通常是通过把一批更改积蓄起来、使之同时生效而实现的。这样做的好处是可以大大提高这些更新的效率。换句话说,事务可以使脚本更快,而且可能更健壮(不过需要正确地使用事务才能获得这样的好处)。
不幸的是,并不是每种数据库都支持事务(mysql5支持事务,mysql4我不知道),所以当第一次打开连接时,pdo 需要在所谓的“自动提交(auto-commit)”模式下运行。自动提交模式意味着,如果数据库支持事务,那么您所运行的每一个查询都有它自己的隐式事务,如果数据库不支持事务,每个查询就没有这样的事务。如果您需要一个事务,那么必须使用 pdo::begintransaction() 方法来启动一个事务。如果底层驱动程序不支持事务,那么将会抛出一个 pdoexception(无论错误处理设置是怎样的:这总是一个严重错误状态)。在一个事务中,可以使用 pdo::commit() 或 pdo::rollback() 来结束该事务,这取决于事务中运行的代码是否成功。
当脚本结束时,或者当一个连接即将被关闭时,如果有一个未完成的事务,那么 pdo 将自动回滚该事务。这是一种安全措施,有助于避免在脚本非正常结束时出现不一致的情况 —— 如果没有显式地提交事务,那么假设有某个地方会出现不一致,所以要执行回滚,以保证数据的安全性。
//例子来自http://www.ibm.com/developerworks/cn/db2/library/techarticles/dm-0505furlong/index.html try { $dbh = new pdo('odbc:sample', 'db2inst1', 'ibmdb2', array(pdo_attr_persistent => true)); echo "connected\n"; $dbh->setattribute(pdo_attr_errmode, pdo_errmode_exception); $dbh->begintransaction(); $dbh->exec("insert into staff (id, first, last) values (23, 'joe', 'bloggs')"); $dbh->exec("insert into salarychange (id, amount, changedate) values (23, 50000, now())"); $dbh->commit(); } catch (exception $e) { $dbh->rollback(); echo "failed: " . $e->getmessage(); } |
并不是一定要在事务中作出更新。您也可以发出复杂的查询来提取数据,还可以使用那种信息构建更多的更新和查询。当事务在活动时,可以保证其他人在工作进行当中无法作出更改。事实上,这不是 100% 的正确,但如果您之前没有听说过事务的话,这样介绍也未尝不可。
★预处理语句和存储过程
很多更成熟的数据库都支持预处理语句的概念。什么是预处理语句?您可以把预处理语句看作您想要运行的 sql 的一种编译过的模板,它可以使用变量参数进行定制。预处理语句可以带来两大好处:
查询只需解析(或准备)一次,但是可以用相同或不同的参数执行多次。当查询准备好后,数据库将分析、编译和优化执行该查询的计划。对于复杂的查询,这个过程要花比较长的时间,如果您需要以不同参数多次重复相同的查询,那么该过程将大大降低应用程序的速度。通过使用预处理语句,可以避免重复分析/编译/优化周期。简言之,预处理语句使用更少的资源,因而运行得更快。
提供给预处理语句的参数不需要用引号括起来,驱动程序会处理这些。如果应用程序独占地使用预处理语句,那么可以确保没有 sql 入侵发生。(然而,如果您仍然将查询的其他部分建立在不受信任的输入之上,那么就仍然存在风险)。
预处理语句是如此有用,以致 pdo 实际上打破了在目标 4 中设下的规则:如果驱动程序不支持预处理语句,那么 pdo 将仿真预处理语句。
实例:pdo的应用例子:
$dbms='mysql'; //数据库类型 oracle 用odi,对于开发者来说,使用不同的数据库,只要改这个,不用记住那么多的函数了 $host='localhost'; //数据库主机名 $dbname='test'; //使用的数据库 $user='root'; //数据库连接用户名 $pass=''; //对应的密码 $dsn="$dbms:host=$host;dbname=$dbname"; class db extends pdo { public function __construct(){ try { parent::__construct("$globals[dsn]", $globals['user'], $globals['pass']); } catch (pdoexception $e) { die("error: " . $e->__tostring() . " "); } } public final function query($sql){ try { return parent::query($this->setstring($sql)); }catch (pdoexception $e){ die("error: " . $e->__tostring() . " "); } } private final function setstring($sql){ echo "我要处理一下$sql"; return $sql; } } $db=new db(); $db->setattribute(pdo::attr_case, pdo::case_upper); foreach ($db->query('select * from xxxx_menu') as $row) { print_r($row); } $db->exec('delete from `xxxx_menu` where mid=43'); ?> |
4.php手册
★ 至此,您已经通过 pdo 连接到了 mysql,在发出查询之前,您应该理解 pdo 是如何管理事务的。如果之前没有接触过事务,那么首先要知道事务的 4 个特征:原子性(atomicity)、一致性(consistency)、独立性(isolation)和持久性(durability),即 acid。用外行人的话说,对于在一个事务中执行的任何工作,即使它是分阶段执行的,也一定可以保证该工作会安全地应用于数据库,并且在工作被提交时,不会受到来自其他连接的影响。事务性工作可以根据请求自动撤销(假设您还没有提交它),这使得脚本中的错误处理变得更加容易。 事务通常是通过把一批更改积蓄起来、使之同时生效而实现的。这样做的好处是可以大大提高这些更新的效率。换句话说,事务可以使脚本更快,而且可能更健壮(不过需要正确地使用事务才能获得这样的好处)。 不幸的是,并不是每种数据库都支持事务(mysql5支持事务,mysql4我不知道),所以当第一次打开连接时,pdo 需要在所谓的“自动提交(auto-commit)”模式下运行。自动提交模式意味着,如果数据库支持事务,那么您所运行的每一个查询都有它自己的隐式事务,如果数据库不支持事务,每个查询就没有这样的事务。如果您需要一个事务,那么必须使用 pdo::begintransaction() 方法来启动一个事务。如果底层驱动程序不支持事务,那么将会抛出一个 pdoexception(无论错误处理设置是怎样的:这总是一个严重错误状态)。在一个事务中,可以使用 pdo::commit() 或 pdo::rollback() 来结束该事务,这取决于事务中运行的代码是否成功。 当脚本结束时,或者当一个连接即将被关闭时,如果有一个未完成的事务,那么 pdo 将自动回滚该事务。这是一种安全措施,有助于避免在脚本非正常结束时出现不一致的情况 —— 如果没有显式地提交事务,那么假设有某个地方会出现不一致,所以要执行回滚,以保证数据的安全性。 本文链接http://www.cxybl.com/html/wlbc/Php/20120531/27131.html

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.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

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

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

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.
