Home > Backend Development > PHP Tutorial > PHP PDO class tutorial_PHP tutorial

PHP PDO class tutorial_PHP tutorial

WBOY
Release: 2016-07-13 17:35:27
Original
891 people have browsed it

POD扩展是在PHP5中加入,该扩展提供PHP内置类 PDO来对数据库进行访问,不同数据库使用相同的方法名,解决数据库连接不统一的问题。
PDO的目标

提供一种轻型、清晰、方便的 API
统一各种不同 RDBMS 库的共有特性,但不排除更高级的特性。
通过 PHP 脚本提供可选的较大程度的抽象/兼容性。

PDO的特点:

性能。PDO 从一开始就吸取了现有数据库扩展成功和失败的经验教训。因为 PDO 的代码是全新的,所以我们有机会重新开始设计性能,以利用 PHP 5 的最新特性。
能力。PDO 旨在将常见的数据库功能作为基础提供,同时提供对于 RDBMS 独特功能的方便访问。
简单。PDO 旨在使您能够轻松使用数据库。API 不会强行介入您的代码,同时会清楚地表明每个函数调用的过程。
运行时可扩展。PDO 扩展是模块化的,使您能够在运行时为您的数据库后端加载驱动程序,而不必重新编译或重新安装整个 PHP 程序。例如,PDO_OCI 扩展会替代 PDO 扩展实现 oracle 数据库 API。还有一些用于 MySQL、PostgreSQL、ODBC 和 Firebird 的驱动程序,更多的驱动程序尚在开发。 [separator]


安装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
各各扩展所对应的数据库是:
Driver name Supported databases
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);
?>

Because the setAttribute() method is used in the above, the two parameters are put in to force the field name to uppercase. Listed below are the parameters of PDO::setAttribute(): PDO::ATTR_CASE: Force the column name into a format, as detailed as follows (second parameter):

PDO::CASE_LOWER: Force column names to be lowercase.
PDO::CASE_NATURAL: Column names are in the original way
PDO::CASE_UPPER: Force column names to be uppercase.
PDO::ATTR_ERRMODE: Error message.
PDO::ERRMODE_SILENT: Does not display error message, only error code.
PDO::ERRMODE_WARNING: Displays warning error.
PDO::ERRMODE_EXCEPTION: Throws exception.
PDO: :ATTR_ORACLE_NULLS (valid not only for ORACLE, but also for other databases): ) Specifies the corresponding value in php for the NULL value returned by the database.
PDO::NULL_NATURAL: unchanged.
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- in the example >setFetchMode(PDO::FETCH_ASSOC); is PDOStatement::setFetchMode(), a declaration of the return type.
are as follows:
PDO::FETCH_ASSOC -- Associative array form
PDO::FETCH_NUM -- Numeric index array form
PDO::FETCH_BOTH -- Both array forms are available, which is missing Provincial
PDO::FETCH_OBJ - in the form of an object, similar to the previous mysql_fetch_object()
For more return type declarations (PDOStatement::method name), see the manual.

Insert, update, delete data,
$db->exec("Delete FROM `xxxx_menu` where mid=43");

A brief summary of the above operations:
The query operations are mainly PDO::query(), PDO::exec(), and PDO::prepare().
PDO::query() is mainly used for operations that return recorded results, especially Select operations.
PDO::exec() is mainly used for operations that do not return a result set, such as Insert, Update, and Delete For other operations, the result it returns is the number of columns affected by the current operation.
PDO::prepare() is mainly a preprocessing operation. You need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and is quite powerful. It cannot be described simply in this article. If you understand, you can refer to the manual and other documents.

The main operations for obtaining the result set are: PDOStatement::fetchColumn(), PDOStatement::fetch(), PDOStatement::fetchALL().
PDOStatement::fetchColumn() is a field of the first record specified in the fetch result. The default is the first field.
PDOStatement::fetch() is used to obtain a record.
PDOStatement::fetchAll() is used to obtain all records into one. To obtain the results, you can set the type of the required result set through PDOStatement::setFetchMode.

There are two other peripheral operations, one is PDO::lastInsertId() and PDOStatement::rowCount(). PDO::lastInsertId() returns the last insertion operation, and the primary key column type is the last auto-increment ID.
PDOStatement::rowCount() is mainly used for the result set affected by PDO::query() and PDO::prepare()'s Delete, Insert, and Update operations. It is invalid for the PDO::exec() method and Select operation. .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508330.htmlTechArticlePOD extension is added in PHP5. This extension provides PHP built-in class PDO to access the database and is used by different databases. The same method name solves the problem of inconsistent database connections. PDO's...
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template