Tutorial for the PDO class in PHP

Source: Internet
Author: User
Keywords Tutorial for the PDO class in PHP
Tags ibm db2 rowcount

Pod extension is added in php5, which provides PHP built-in class PDO to access the database, different databases use the same method name, to solve the problem of non-uniform database connection.
The goal of PDO

Provides a lightweight, clear, and convenient API
Unify the common features of different RDBMS libraries, but not exclude more advanced features.
Provides an optional, large degree of abstraction/compatibility through PHP scripting.

Features of PDO:

Performance. PDO has learned from the outset the successes and failures of existing database extensions. Because PDO's code is brand new, we have the opportunity to start designing performance again to take advantage of the latest features of PHP 5.
Ability. PDO is designed to provide the basis for common database functionality while providing easy access to the unique features of the RDBMS.
Simple. PDO is designed to make it easy to use your database. The API does not force you into your code, and it clearly shows the process of each function call.
The runtime is extensible. The PDO extension is modular, allowing you to load drivers at run time for your database backend without having to recompile or reinstall the entire PHP program. For example, the Pdo_oci extension implements the Oracle database API instead of the PDO extension. There are also drivers for MySQL, PostgreSQL, ODBC, and Firebird, and more drivers are still being developed. [Separator]


Installing PDO
I am here for the PDO extension under Windows development, if you want to install the configuration under Linux, please look elsewhere.
Version requirements: php5.1 and later version of the package has been brought, php5.0.x to pecl.php.net to download, put in your extension library, PHP is located in the folder of the Ext folder, the manual said the version before 5.0 can not run the PDO extension. Configuration:
Modify your php.ini profile so that it supports PDO. (php.ini this thing is not understood, first figure out, to modify the call your Phpinfo () function shows the php.ini) extension=php_ Pdo.dll in front of the semicolon is removed, the other is a PHP configuration file comment symbol, this extension is necessary. and down there.
; 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
The corresponding databases for each extension are:
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
What kind of database would you like to use, as long as you put the appropriate pre-extension comment symbol ";" get rid of it.

Using PDO
I assume that you have installed MySQL, if not installed, trouble first try to install, my is mysql5.0.22, night passers-by with the MySQL 4.0.26 can also be used.  
Connection to database:
We analyze the PDO connection database using the following example,
!--? php
$dbms = ' MySQL ';  Database type Oracle with ODI, for developers, using a different database, just change this, do not remember so many functions
$host = ' localhost ';//database hostname
$dbName = ' Test ';   Database used
$user = ' root ';     Database connection user name
$pass = '; The corresponding password
$dsn = "$dbms: host= $host;d bname= $dbName";
  try {
$dbh = new PDO ($DSN, $user, $pass);//Initialize a PDO object to create a database connection object $DBH
echo "Connection succeeded
";
/* You can also perform a search operation
foreach ($dbh->query (' Select * from FOO ') as $row) {
Print_r ($row);//You can use Echo ($GLOBAL); To these values
}
*/
$DBH = null;
} catch (Pdoexception $e) {
Die ("error!:"). $e->getmessage (). "
");
}
//Default this is not a long connection, if you need a long database connection, you need to add one last parameter: Array (pdo::attr_persistent = True) becomes this:
$db = new PDO ($DSN, $user, $ Pass, array (pdo::attr_persistent = true));
?

Database query:
We have made a query above, and we can use the following query:
$db->setattribute (Pdo::attr_case, Pdo::case_upper); Setting properties
$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, the two parameters are placed, and the field names are cast to uppercase. The following is a list of Pdo::setattribute () Parameters: Pdo::attr_case: Force the column name to be a format, as detailed below (the second parameter):

Pdo::case_lower: Enforces that the column name is lowercase.
Pdo::case_natural: Column names are in the original way
Pdo::case_upper: Force column name to uppercase.
Pdo::attr_errmode: Error prompt.
Pdo::errmode_silent: The error message is not displayed, only the error code is displayed.
Pdo::errmode_warning: A warning error is displayed.
Pdo::errmode_exception: Throws an exception.
Pdo::attr_oracle_nulls (not just ORACLE valid, other databases are also valid):) Specifies the value that the null value returned by the database corresponds to in PHP.
Pdo::null_natural: no change.
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 is 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) In the example, is a declaration of the return type of Pdostatement::setfetchmode ().
There are the following:
PDO::FETCH_ASSOC--Associative array form
Pdo::fetch_num--Digital Index array form
Pdo::fetch_both--both array form, this is the default
Pdo::fetch_obj-In the form of an object, similar to the previous mysql_fetch_object ()
See the Manual for more return type declarations (pdostatement:: Method names).

Insert, UPDATE, delete data,
$db->exec ("Delete from ' Xxxx_menu ' where mid=43");

Simply summarize the above actions:
The query operation is mainly Pdo::query (), Pdo::exec (), PDO::p repare ().
Pdo::query () is primarily used for operations that have logged results returned, in particular the select operation,
Pdo::exec () is primarily for operations that do not have a result set, such as INSERT, Update, delete, and so on, which returns the number of columns affected by the current operation.
PDO::p repare () is mainly pre-processing operations, need to $rs->execute () to perform preprocessing inside the SQL statement, this method can bind parameters, the function is relatively strong, not this article can be simple to understand, you can refer to manuals and other documents.

The main operations for getting result sets are: Pdostatement::fetchcolumn (), Pdostatement::fetch (), Pdostatement::fetchall ().
Pdostatement::fetchcolumn () is a field that gets the result that specifies the first record, and the default is the first field.
Pdostatement::fetch () is used to get a record,
Pdostatement::fetchall () is to get all recordsets into one, and get results can be set by Pdostatement::setfetchmode to the type that requires the result collection.

There are also two peripheral operations, one of which is Pdo::lastinsertid () and Pdostatement::rowcount (). Pdo::lastinsertid () is the last insert operation returned, and the primary key column type is the final self-increment ID.
Pdostatement::rowcount () is primarily used for pdo::query () and PDO::p Repare () for the result set affected by the delete, Insert, update operation, for Pdo::exec () Method and select operation are not valid.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.