PDO contains three predefined classes: pDO, pdostatement, and pdoexception.

Source: Internet
Author: User
Tags dsn rowcount
Represents a connection between a PHP and a database.

Method: pDO-constructor to build a new PDO object
Begintransaction-start transaction
Commit-Submit a transaction
Errorcode-returns an error code from the database, if any
Errorinfo-returns an array containing error information from the database, if any
Exec-execute an SQL statement and return the affected number of rows
Getattribute-returns a database connection attribute
Lastinsertid-returns the row (ID) of the last inserted row to the database)
Prepare-prepare an SQL statement for execution
Query-execute an SQL statement and return a result set
Quote-returns a string with quotation marks added so that it can be used in SQL statements.
Rollback-roll back a transaction
Setattribute-set a database connection attribute
Ii. pdostatement
Indicates a pre-processing statement and the associated result set after the statement is executed ). Method: bindcolumn-bind a PHP variable to the output column in The result set.
Bindparam-bind a PHP variable to a parameter in a preprocessing statement
Bindvalue-bind a value to a parameter in the processing statement
Closecursor-close the cursor so that the statement can be executed again
Columncount-Number of columns in the returned result set
Errorcode-returns an error code from the statement, if any
Errorinfo-returns an array containing error information from the statement. If yes
Execute-execute a preprocessing statement
Fetch-extract a row from the result set
Fetchall-retrieve an array containing all rows from the constructor
Fetchcolumn-data in a column in the returned result set
Getattribute-returns a pdostatement attribute.
Getcolumnmeta-structure of a column in the returned result set (metadata ?)
Nextrowset-return the next result set
Rowcount-returns the number of rows affected by SQL statement execution.
Setattribute-set a pdostatement attribute
Setfetchmode-set the Data Retrieval Method for pdostatement
3. pdoexception
Returns an error triggered by PDO. You cannot throw a pdoexception from your code. // Pdoexception class:
Class pdoexception extends exception
// Corresponds to PDO: errorinfo ()
// Or pdostatement: errorinfo ()
Public $ errorinfo = NULL;
// Normalized error message
// Use exception: getmessage () to get it
Protected $ message;
// Sqlstate error code
// Use exception: getcode () to get it
Protected $ code;
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 (): pDO: attr_case: force the column name to be in a format, as detailed (second parameter): pDO: case_lower: the column name must be in lower case. PDO: case_natural: the column name is in the original format: pDO: case_upper: the column name is forcibly capitalized. 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, arr Ay (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-& gt; 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 () 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-& gt; execute () to execute the SQL statement 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. So far, you have connected to MySQL through PDO. Before sending a query, you should understand how PDO manages transactions. If you have never touched on a transaction before, you must first understand the four features of the transaction: atomicity, consistency, isolation, and durability ), acid. In layman's words, any work performed in a transaction can be safely applied to databases even if it is executed in stages, when a job is submitted, it is not affected by other connections. Transactional work can be automatically revoked based on the request (assuming you have not submitted it), which makes it easier to handle errors in the script.
Transactions are usually implemented by saving up a batch of changes to make them take effect at the same time. This can greatly improve the efficiency of these updates. In other words, a transaction can make the script faster and more robust (but you need to use the transaction correctly to get this benefit ).
Unfortunately, not every database supports transactions (mysql5 supports transactions, I don't know about mysql4), so when the connection is opened for the first time, PDO needs to run in the so-called "auto-commit" mode. The automatic commit Mode means that if the database supports transactions, each query you run has its own implicit transaction. If the database does not support transactions, no such transaction exists for each query. If you need a transaction, you must use the PDO: begintransaction () method to start a transaction. If the underlying driver does not support transactions, a pdoexception will be thrown (regardless of the error processing settings: This is always a serious error state ). In a transaction, you can use PDO: Commit () or PDO: rollback () to end the transaction, depending on whether the code running in the transaction is successful.
When the script ends, or when a connection is about to be closed, if there is an unfinished transaction, PDO will automatically roll back the transaction. This is a security measure that helps avoid inconsistencies when the script ends abnormally-if the transaction is not explicitly committed, it is assumed that there will be inconsistencies somewhere, therefore, perform rollback to ensure data security.
// Example from http://www.ibm.com/developerworks/cn/db2/library/techarticles/dm-0505furlong/index.html
Try {
$ DBH = new PDO ('odbc: sample', 'db2inst1', 'ibmdb ',
Array (pdo_attr_persistent = & gt; true ));
Echo "connected/N ";
$ DBH-& gt; setattribute (pdo_attr_errmode, pdo_errmode_exception );
$ DBH-& gt; begintransaction ();
$ DBH-& gt; Exec ("insert into staff (ID, first, last) values (23, 'job', 'bloggs ')");
$ DBH-& gt; Exec ("insert into salarychange (ID, amount, changedate)
Values (23,500 00, now ())");
$ DBH-& gt; Commit ();

} Catch (exception $ e ){
$ DBH-& gt; rollback ();
Echo "failed:". $ e-& gt; getmessage ();
} In the preceding example, assume that we create a group of entries for a new employee. This employee has an ID number, that is, 23. In addition to entering the basic data of this person, we also need to record the employee's salary. The two updates are easy to complete, but by including the two updates in the begintransaction () and commit () calls, you can ensure that others cannot see the changes before the changes are completed. If an error occurs, the catch block can roll back all the changes that have occurred since the beginning of the transaction and print an error message. It is not necessary to update the transaction. You can also issue complex queries to extract data, and use that information to create more updates and queries. When a transaction is active, other persons cannot make changes during work. In fact, this is not 100% correct, but if you have never heard of a transaction before, it is not worth mentioning.★Many more mature databases support the concept of pre-processing statements. What is a pre-processing statement? You can regard the pre-processing statement as a compiled template of the SQL statement you want to run. It can be customized using variable parameters. The pre-processing statement can bring two benefits: the query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is ready, the database will analyze, compile, and optimize the plan for executing the query. For complex queries, this process takes a long time. If you need to repeat the same query multiple times with different parameters, this process will greatly reduce the speed of the application. By using preprocessing statements, you can avoid repeated analysis, compilation, and optimization cycles. In short, preprocessing statements use fewer resources and therefore run faster.
Parameters provided to the pre-processing statement do not need to be enclosed in quotation marks. The driver will process these parameters. If the application exclusively uses preprocessing statements, it can ensure that no SQL intrusion occurs. (However, if you still establish other parts of the query on untrusted input, there is still a risk ).
Preprocessing statements are so useful that PDO actually breaks the Rule Set in Objective 4: If the driver does not support preprocessing statements, PDO will simulate preprocessing statements. Example: <? PHP
$ DBMS = 'mysql'; // Database Type Oracle uses Odi. for developers, if they use different databases, you don't need to remember so many functions $ host = 'localhost'; // Database Host Name $ dbname = 'test'; // the database used $ user = 'root '; // database connection username $ pass = ''; // password $ 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 (). "<br/> ");

Public final function query ($ SQL ){
Try {
Return parent: Query ($ this-& gt; setstring ($ SQL ));
} Catch (pdoexception $ e ){
Die ("error:". $ e-& gt ;__ tostring (). "<br/> ");

Private final function setstring ($ SQL ){
Echo "I want to handle $ SQL ";
Return $ SQL;
} $ Db = new dB ();
$ Db-& gt; setattribute (PDO: attr_case, PDO: case_upper );
Foreach ($ db-& gt; query ('select * From xxxx_menu ') as $ row ){
Print_r ($ row );
$ Db-& gt; Exec ('delete from 'xxxx _ menu 'Where mid = 43 ');
? & Gt;

This description is quite complete. It was previously collected on the internet, hoping to bring a small value to those who need it.

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.