Php pdo tutorial _ PHP Tutorial-php Tutorial

Source: Internet
Author: User
Tags ibm db2
Php pdo class tutorial. The POD extension is added to PHP5, which provides the PHP built-in PDO class to access the database. different databases use the same method name to solve the problem of inconsistent database connections. PDO

The POD extension is added to PHP5, which provides the PHP built-in PDO class to access the database. different databases use the same method name to solve the problem of inconsistent database connections.
PDO goals

Provides a lightweight, clear, and convenient API
The common features of different RDBMS databases are unified, but more advanced features are not excluded.
PHP scripts provide optional abstract/compatibility.

PDO features:

Performance. From the very beginning, PDO learned from the success and failure of existing database expansion. Because the PDO code is brand new, we have the opportunity to design performance again to take advantage of the latest features of PHP 5.
Capability. PDO is designed to provide common database functions as the basis and provide convenient access to the unique functions of RDBMS.
Simple. PDO is designed to make it easy to use databases. The API does not forcibly intervene in your code and clearly shows the process of calling each function.
It can be expanded during runtime. The PDO extension is modular, allowing you to load drivers at the backend of your database at runtime without re-compiling or re-installing the entire PHP program. For example, the PDO_OCI extension replaces the PDO extension to implement the oracle database API. There are also some drivers for MySQL, PostgreSQL, ODBC, and Firebird. more drivers are still under development. [Separator]


Install PDO
I am using the PDO extension developed in WINDOWS. if you want to install the configuration in Linux, go to other places to find it.
Version requirements: php5.1 and later versions are included in the program package; php5.0.x is to be downloaded from pecl.php.net and placed in your Extension Library, that is, the ext folder in the PHP folder; in the manual, versions earlier than 5.0 cannot run PDO extensions. Configuration:
Modify your php. ini configuration file to support pdo. (php. if you do not understand ini, first make it clear that you need to modify the php code displayed by calling your phpinfo () function. ini) remove the semicolon before extension = php_pdo.dll, which is the annotation symbol of the php configuration file. this extension is required. Down
; 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 databases corresponding to 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
You only need to remove the annotator ";" before the corresponding extension to which database you want to use.

Use PDO
Let me assume that you have installed mysql. if you haven't installed MySQL, try to install it first. mysql5.0.22 is for me, and mysql4.0.26 is for night travelers.
Database connection:
We use the following example to analyze how PDO connects to the database,
$ Dbms = mysql; // Database type oracle uses ODI. for developers, if they use different databases, they do not need to remember so many functions.
$ Host = localhost; // database host name
$ DbName = test; // database used
$ User = root; // database connection username
$ Pass =; // password
$ Dsn = "$ dbms: host = $ host; dbname = $ dbName ";
Try {
$ Dbh = new PDO ($ dsn, $ user, $ pass); // initialize a PDO object, that is, create a database connection object $ dbh
Echo "connection successful
";
/* You can perform a search operation.
Foreach ($ dbh-> query (Select * from FOO) as $ row ){
Print_r ($ row); // you can use echo ($ GLOBAL); to view these values
}
*/
$ Dbh = null;
} Catch (PDOException $ e ){
Die ("Error! : ". $ E-> getMessage ()."
");
}
// By default, this is not a persistent connection. if you need a persistent connection to the database, you need to add the following parameter: array (PDO: ATTR_PERSISTENT => true:
$ Db = new PDO ($ dsn, $ user, $ pass, array (PDO: ATTR_PERSISTENT => true ));
?>

Database query:
We have performed a query above, and we can also use the following query:
$ Db-> setAttribute (PDO: ATTR_CASE, PDO: CASE_UPPER); // Set attributes
$ 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, place the two parameters and forcibly convert the field name to uppercase. The following lists the parameters with multiple PDO: setAttribute () parameters: PDO: ATTR_CASE: force the column name to be in a format, as detailed below (second parameter ):

PDO: CASE_LOWER: The column name must be in lower case.
PDO: CASE_NATURAL: column names follow the original method
PDO: CASE_UPPER: force column names to be uppercase.
PDO: ATTR_ERRMODE: error message.
PDO: ERRMODE_SILENT: only error codes are displayed.
PDO: ERRMODE_WARNING: displays a warning error.
PDO: ERRMODE_EXCEPTION: throw an exception.
PDO: ATTR_ORACLE_NULLS (not only effective in ORACLE, but also in other databases): specifies the value of the NULL value returned by the database in php.
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.
In the example, $ rs-> setFetchMode (PDO: FETCH_ASSOC); is PDOStatement: setFetchMode (), which declares the return type.
There are:
PDO: FETCH_ASSOC -- join array form
PDO: FETCH_NUM -- numeric index array format
PDO: FETCH_BOTH -- both arrays are available, which is the default
PDO: FETCH_OBJ -- according to the object form, similar to the previous mysql_fetch_object ()
For more information about the return type declaration (PDOStatement: method name), see the manual.

Insert, update, and delete data,
$ Db-> exec ("Delete FROM 'xxxx _ menu 'where mid = 43 ");

Briefly summarize the above operations:
Query operations are mainly PDO: query (), PDO: exec (), PDO: prepare ().
PDO: query () is mainly used for operations that return records, especially Select operations,
PDO: exec () is mainly used for operations that do not return result sets, such as Insert, Update, Delete, and so on. it returns the number of columns affected by the current operation.
PDO: prepare () is mainly used for preprocessing. you need to use $ rs-> execute () to execute the SQL statements in the preprocessing. this method can bind parameters and has powerful functions, this document is not a simple description. you can refer to the manual and other documents.

To obtain a result set, perform the following operations: PDOStatement: fetchColumn (), PDOStatement: fetch (), and PDOStatement: fetchALL ().
PDOStatement: fetchColumn () is a field of the first record specified in the result. the default value is the first field.
PDOStatement: fetch () is used to obtain a record,
PDOStatement: fetchAll () is to obtain all the record sets to one. you can use PDOStatement: setFetchMode to set the type of the desired result set.

There are also two peripheral operations: PDO: lastInsertId () and PDOStatement: rowCount (). PDO: lastInsertId () is the last insert operation, and the primary key column type is the last auto-increment ID of auto-increment.
PDOStatement: rowCount () is the result set affected by the Delete, Insert, and Update operations on PDO: query () and PDO: prepare :: the exec () method and Select operation are invalid.

PDO is used to access the database. different databases use the same method name to solve the problem of inconsistent database connections. PDO...

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.