PHPPDO function library details

Source: Internet
Author: User
PDO is a "database access abstraction layer" that unifies access interfaces of various databases. Compared with mysql and mysqli function libraries, PDO makes cross-database use more friendly; compared with ADODB and MDB2, PDO is more efficient.

PDO is a "database access abstraction layer" that unifies access interfaces of various databases. Compared with mysql and mysqli function libraries, PDO makes cross-database use more friendly; compared with ADODB and MDB2, PDO is more efficient.

At present, there is a long way to implement the "database abstraction layer". Using the "database access abstraction layer" such as PDO is a good choice.

PDO contains three predefined classes.

PDO contains three predefined classes: PDO, PDOStatement, and PDOException.

I. PDO

PDO->-indicates the rollback start point
PDO-> commit ()-indicates the rollback end point and executes the SQL
PDO->__ construct ()-create a PDO-Linked database instance
PDO-> errorCode ()-Get error code
PDO-> errorInfo ()-Get error information
PDO-> exec ()-processes an SQL statement and returns the number of affected items
PDO-> getAttribute ()-Get the attribute of a "database connection object"
PDO-> getAvailableDrivers ()-Get a valid PDO drive name
PDO-> lastInsertId ()-Get the primary key value of the last data entry written
PDO-> prepare ()-generate a "query object"
PDO-> query ()-processes an SQL statement and returns a "PDOStatement"
PDO-> quote ()-add quotation marks for strings in an SQL statement
PDO-> rollBack ()-Execute rollBack
PDO-> setAttribute ()-set attributes for a "database connection object"

Ii. PDOStatement

PDOStatement-> bindColumn ()-Bind a column to a PHP variable
PDOStatement-> bindParam ()-Binds a parameter to the specified variable name
PDOStatement-> bindValue ()-Binds a value to a parameter
PDOStatement-> closeCursor ()-Closes the cursor, enabling the statement to be executed again.
PDOStatement-> columnCount ()-Returns the number of columns in the result set
PDOStatement-> errorCode ()-Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement-> errorInfo ()-Fetch extended error information associated with the last operation on the statement handle
PDOStatement-> execute ()-Executes a prepared statement
PDOStatement-> fetch ()-Fetches the next row from a result set
PDOStatement-> fetchAll ()-Returns an array containing all of the result set rows
PDOStatement-> fetchColumn ()-Returns a single column from the next row of a result set
PDOStatement-> fetchObject ()-Fetches the next row and returns it as an object.
PDOStatement-> getAttribute ()-Retrieve a statement attribute
PDOStatement-> getColumnMeta ()-Returns metadata for a column in a result set
PDOStatement-> nextRowset ()-Advances to the next rowset in a multi-rowset statement handle
PDOStatement-> rowCount ()-Returns the number of rows affected by the last SQL statement
PDOStatement-> setAttribute ()-Set a statement attribute
PDOStatement-> setFetchMode ()-Set the default fetch mode for this statement

PDO is a "database access abstraction layer" that unifies access interfaces of various databases. Compared with mysql and mysqli function libraries, PDO makes cross-database use more friendly; compared with ADODB and MDB2, PDO is more efficient. At present, there is a long way to implement the "database abstraction layer". Using the "database access abstraction layer" such as PDO is a good choice.

PDO contains three predefined classes.

PDO contains three predefined classes: PDO, PDOStatement, and PDOException.

I. PDO

PDO->-indicates the rollback start point
PDO-> commit ()-indicates the rollback end point and executes the SQL
PDO-> rollBack ()-Execute rollBack
PDO->__ construct ()-create a PDO-Linked database instance
PDO-> errorCode ()-Get error code
PDO-> errorInfo ()-Get error information
PDO-> exec ()-processes an SQL statement and returns the number of affected items
PDO-> getAttribute ()-Get the attribute of a "database connection object"
PDO-> getAvailableDrivers ()-Get a valid PDO drive name
PDO-> lastInsertId ()-Get the primary key value of the last data entry written
PDO-> prepare ()-generate a "query object"
PDO-> query ()-processes an SQL statement and returns a "PDOStatement"
PDO-> quote ()-add quotation marks for strings in an SQL statement
PDO-> setAttribute ()-set attributes for a "database connection object"

1) database connection in PDO
$ Dsn = 'mysql: dbname = ent; host = 127.0.0.1 ′;
$ User = 'root ';
$ Password = '000000 ′;
Try {
$ Dbh = new PDO ($ dsn, $ user, $ password, array (PDO: ATTR_PERSISTENT => true ));
$ Dbh-> query ('set names utf8 ;');
Foreach ($ dbh-> query ('select * from tpm_juese ') as $ row ){
Print_r ($ row );
}
} Catch (PDOException $ e ){
Echo 'Connection failed: '. $ e-> getMessage ();
}

Many Web applications are optimized by using persistent connections to databases. Persistent connections are not closed when the script ends,
On the contrary, it will be cached and reused when another script requests a connection through the same identity.
The cache of persistent connections allows you to avoid the resource consumption of deploying a new connection every time the script needs to talk to the database, making your Web application faster.
The array (PDO: ATTR_PERSISTENT => true) in the above instance sets the connection type to persistent connection.

2) Transactions in PDO
PDO->, PDO-> commit (), PDO-> rollBack () are used together when the rollBack function is supported. The PDO-> method indicates the start point, the PDO-> commit () method indicates the end point of the rollBack, and the SQL statement is executed. The PDO-> rollBack () method performs the rollBack.
Try {
$ Dbh = new PDO ('mysql: host = localhost; dbname = test', 'root ',");
$ Dbh-> query ('set names utf8 ;');
$ Dbh-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );

$ Dbh->;
$ Dbh-> exec ("insert into 'test'. 'table' ('name', 'age') VALUES ('mick', 22 );");
$ Dbh-> exec ("insert into 'test'. 'table' ('name', 'age') VALUES ('lily', 29 );");
$ Dbh-> exec ("insert into 'test'. 'table' ('name', 'age') VALUES ('Susan ', 21 );");
$ Dbh-> commit ();

} Catch (Exception $ e ){
$ Dbh-> rollBack ();
Echo "Failed:". $ e-> getMessage ();
}
?>
Now you have established a connection through PDO. before deploying a query, you must understand how PDO manages transactions. If you have never encountered transaction processing before (for a brief introduction), they provide four main features: Atomicity, Consistency, independence, and durability (Atomicity, Consistency, isolation and Durability, ACID) in general, when all the work in a transaction is committed, even if it is executed in stages, it must be securely applied to the database, it is not affected by other connections. The transaction can also be easily canceled automatically when an error occurs in the request.

A typical use of transactions is to "save" batch changes and execute them immediately. In this way, the update efficiency will be improved thoroughly. In other words, transactions can make your scripts faster and more robust (you still need to use them correctly to achieve this advantage ).

Unfortunately, not every database supports transactions, so PDO needs to run in the "auto commit" mode when establishing a connection. The automatic commit Mode means that each query you execute has its own implicit transaction processing, no matter whether the database supports transactions or because the database does not support transactions. If you need a transaction, you must use the PDO-> method to create one. If the underlying driver does not support transaction processing, a PDOException will be thrown (it is irrelevant to your Exception Processing settings because it is always a serious error state ). In a transaction, you can end it with PDO-> commit () or PDO-> rollBack (), depending on whether the code in the transaction runs successfully.

When the script ends or a connection is closed, if you still have an unfinished transaction, PDO will automatically roll it back. This is a safe solution for unexpected termination of the script-if you do not explicitly commit the transaction, it will assume that some errors have occurred for your data security, therefore, rollback is performed.

Ii. PDOStatement

PDOStatement-> bindColumn ()-Bind a column to a PHP variable
PDOStatement-> bindParam ()-Binds a parameter to the specified variable name
PDOStatement-> bindValue ()-Binds a value to a parameter
PDOStatement-> closeCursor ()-Closes the cursor, enabling the statement to be executed again.
PDOStatement-> columnCount ()-Returns the number of columns in the result set
PDOStatement-> errorCode ()-Fetch the SQLSTATE associated with the last operation on the statement handle
PDOStatement-> errorInfo ()-Fetch extended error information associated with the last operation on the statement handle
PDOStatement-> execute ()-Executes a prepared statement
PDOStatement-> fetch ()-Fetches the next row from a result set
PDOStatement-> fetchAll ()-Returns an array containing all of the result set rows
PDOStatement-> fetchColumn ()-Returns a single column from the next row of a result set
PDOStatement-> fetchObject ()-Fetches the next row and returns it as an object.
PDOStatement-> getAttribute ()-Retrieve a statement attribute
PDOStatement-> getColumnMeta ()-Returns metadata for a column in a result set
PDOStatement-> nextRowset ()-Advances to the next rowset in a multi-rowset statement handle
PDOStatement-> rowCount ()-Returns the number of rows affected by the last SQL statement
PDOStatement-> setAttribute ()-Set a statement attribute
PDOStatement-> setFetchMode ()-Set the default fetch mode for this statement

3. PDOException

PDO provides three different error handling policies.
1. PDO: ERRMODE_SILENT
This is the default mode. PDO sets simple error codes on statement and database objects. You can use the PDO-> errorCode () and PDO-> errorInfo () methods to check errors; if the error is caused by calling the statement object, you can use the PDOStatement-> errorCode () or PDOStatement-> errorInfo () method on the object to get the error information. If the error is caused by calling the database object, you should call the two methods on the database object.
2. PDO: ERRMODE_WARNING
As an additional error code, PDO sends out a traditional E_WARNING message. This setting is useful in debugging and debugging. If you just want to see what went wrong and don't want to interrupt the program process.
3. PDO: ERRMODE_EXCEPTION
As an attachment for setting the error code, PDO throws a PDOException and sets its attributes to reflect the error code and error information. This setting is also useful in addition to errors, because it will effectively point to an error point in the "enlarge (blow up)" script, very quickly pointing to a possible error area in your code. (Remember: if an exception causes a script interruption, the transaction will be automatically rolled back .)
Exception mode is also very useful, because you can use a structure that is clearer than the traditional PHP-style error handling structure, it uses less code and nesting than quiet mode, and it can also check the return values of each database access more clearly.
For more information about Exceptions in PHP, see the Exceptions section.
PDO uses an error code string based on the SQL-92 SQLSTATE; a specific PDO driver should map its own code to the appropriate SQLSTATE code. The PDO-> errorCode () method returns only a single SQLSTATE code. If you need more targeted information about an error, PDO also provides a PDO-> errorInfo () method, which can return a code containing the SQLSTATE, the error code of the specific database driver and the error string of the specific database driver.

Attribute list:

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.