PHP PDO function Library detailed

Source: Internet
Author: User

PDO is a "database access abstraction Layer" that unifies the access interfaces of various databases, and PDO makes cross-database usage more affinity than MySQL and mysqli libraries, and PDO is more efficient than ADODB and MDB2. For now, implementing a "database Abstraction Layer" is a long way off, and using a "Database access abstraction Layer" like PDO is a good choice.

The PDO contains three predefined classes

The PDO contains three predefined classes, PDO, Pdostatement, and Pdoexception, respectively.

One, PDO

Pdo->begintransaction ()-Indicates the rollback start point
Pdo->commit ()-Indicates the rollback end point and executes the SQL
Pdo->rollback ()-Perform rollback
Pdo->__construct ()-Create an instance of the PDO link database
Pdo->errorcode ()-Get error code
Pdo->errorinfo ()-Get the wrong information
Pdo->exec ()-Processes an SQL statement and returns the number of entries affected
Pdo->getattribute ()-Gets a property of a "Database connection object"
Pdo->getavailabledrivers ()-Get a valid PDO drive name
Pdo->lastinsertid ()-Gets the primary key value of the last piece of data written
Pdo->prepare ()-Generates a "Query object"
Pdo->query ()-Processes an SQL statement and returns a "Pdostatement"
Pdo->quote ()-adds quotation marks to a string in a SQL
Pdo->setattribute ()-Set properties for a database connection object

Detailed 1) database connection in PDO
$dsn = ' mysql:dbname=ent;host=127.0.0.1′;
$user = ' root ';
$password = ' 123456′;
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 for use with persistent connections to the database. Persistent connections are not closed at the end of the script.
Instead, it is cached and re-used when another script requests a connection through the same identity.
Persistent connection caching lets you avoid deploying a new connection's resource consumption every time the script needs to talk to the database, making your web app faster.
The array (pdo::attr_persistent = True) in the above example sets the connection type to persistent connection.

Detail 2) The transaction in PDO
Pdo->begintransaction (), Pdo->commit (), Pdo->rollback () These three methods are used together when the rollback feature is supported. The Pdo->begintransaction () method indicates the starting point, the Pdo->commit () method indicates the rollback end point, and execution Sql,pdo->rollback () performs a rollback.
<?php
try {
$DBH = new PDO (' Mysql:host=localhost;dbname=test ', ' root ', ');
$DBH->query (' Set names utf8; ');
$DBH->setattribute (Pdo::attr_errmode, pdo::errmode_exception);

$DBH->begintransaction ();
$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 that you've established a connection through PDO, you have to figure out how PDO manages the transaction before you deploy the query. If you've never had a transaction before, (here's a quick introduction:) They offer 4 main features: Atomicity, consistency, independence and persistence (atomicity, consistency, isolation and durability,acid) popular point , when all the work in a transaction is committed, even if it is staged in stages, it is guaranteed to be applied securely to the database and not interfered by other connections. Transactional work can also be easily canceled automatically when a request has an error.

A typical use of a transaction is to "save" a batch change and execute it immediately. This will have the benefit of radically improving the efficiency of the update. In other words, transactions can make your scripts faster and potentially 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 a mode that is considered "autocommit" when establishing a connection. Autocommit mode means that each query you execute has its own implicit transaction, whether the database supports transactions or because the database does not support the transaction. If you need a transaction, you must create one using the Pdo->begintransaction () method. If the underlying driver does not support transaction processing, a pdoexception will be thrown (regardless of your exception handling settings, as this is always a serious error state). In one thing, you can end it with Pdo->commit () or Pdo->rollback (), depending on whether the code in the transaction is running successfully.

When the script finishes or a connection is closed, the PDO will automatically roll it back if you have an unhandled transaction. This is a safe scenario for a scenario where the script terminates unexpectedly--if you do not commit the transaction explicitly, it will assume that some errors have occurred and that the rollback is done for the sake of your data security.

Second, 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

Third, pdoexception

PDO provides a different error handling strategy in 3.
1. Pdo::errmode_silent
This is the default mode used. PDO will set simple error codes on the statement and database objects, and you can use the Pdo->errorcode () and Pdo->errorinfo () methods to check for errors If the error is caused by a call to the statement object, you can use the Pdostatement->errorcode () or Pdostatement->errorinfo () method on that object to get the error message. If the error is caused by a call to the database object, you should call the two methods on the database object.
2. pdo::errmode_warning
PDO will emit a traditional e_warning message as an addition to the setup error code. This setting is useful in debugging and debug, if you just want to see what's going on and don't want to interrupt the process.
3. Pdo::errmode_exception
As an attachment that sets the error code, PDO throws an Pdoexception exception and sets its properties to reflect the error code and error message. This setting is useful in addition to errors, because he will effectively "zoom in (Blow up)" The error point in the script, very quickly point to a possible error area in your code. (Remember: If the exception causes the script to break, the transaction is automatically rolled back.) )
The exception mode is also useful because you can use a much clearer structure-handling error than the traditional PHP-style error-handling structure, using less code and nesting than quiet mode, and more explicitly checking the return value of each database access.
For more information about exceptions in PHP, see the Exceptions section
PDO uses the SQL-92 SQLSTATE-based error code string, and the specific PDO driver should correspond its own code name to the appropriate SQLSTATE code. The Pdo->errorcode () method returns only a single SQLState designator. If you need more targeted information about a bug, PDO also provides a pdo->errorinfo () method that returns a string containing the SQLSTATE code, a specific database-driven error ID, and a specific database-driven error description.

<?php
To modify the default error display level
$DBH->setattribute (Pdo::attr_errmode, pdo::errmode_warning);
?>

Property list:

PDO::P Aram_bool
Represents a Boolean type
PDO::P aram_null
Represents a null type in a SQL
PDO::P aram_int
Represents an integer type in sql
PDO::P aram_str
Represents a SQL Char,varchar type in SQL
PDO::P Aram_lob
Represents a large object type in SQL
PDO::P aram_stmt
Represents a recordset type in SQL that has not been supported
PDO::P aram_input_output
Specifies the parameter is an INOUT parameter for a stored procedure. You must bitwise-or the value with an explicit PDO::P aram_* data type.
Pdo::fetch_lazy
Returns the result of each row as an object
Pdo::fetch_assoc
Only returns the result set with the key value as the underlying query, and the data with the same name returns only one
Pdo::fetch_named
Only returns the result set with the key value as the underlying query, and the data with the same name is returned as an array
Pdo::fetch_num
Only returns a result set with a number as the underlying query
Pdo::fetch_both
Also returns the result set with key values and numbers as the underlying query
Pdo::fetch_obj
Returns a result set as an object
Pdo::fetch_bound
Returns the values bound by Pdostatement::bindparam () and Pdostatement::bindcolumn () as variable names
Pdo::fetch_column
Indicates that only one column in the result set is returned
Pdo::fetch_class
Represents the return of a result set in the form of a class
Pdo::fetch_into
Represents the merging of data into an existing class to be returned
Pdo::fetch_func
Pdo::fetch_group
Pdo::fetch_unique
Pdo::fetch_key_pair
Returns the result set as the first key value in the table below, followed by the following table
Pdo::fetch_classtype
Pdo::fetch_serialize
Represents merging data into an existing class and serializing the returned
Pdo::fetch_props_late
Available since PHP 5.2.0
Pdo::attr_autocommit
When set to True, PDO will automatically attempt to stop accepting the delegate and start executing
Pdo::attr_prefetch
Set the size of the data that the application gets in advance, not all the database Oh degree support
Pdo::attr_timeout
Set the value of the connection database timeout
Pdo::attr_errmode
Setting the mode for error handling
Pdo::attr_server_version
Read-only property that represents the server-side database version of the PDO connection
Pdo::attr_client_version
Read-only property that represents the client PDO driver version of the PDO connection
Pdo::attr_server_info
Read-only property that represents the meta information for the PDO-connected server
Pdo::attr_connection_status
Pdo::attr_case
To manipulate the form of a column through content in pdo::case_*
Pdo::attr_cursor_name
Gets or sets the name of the pointer
Pdo::attr_cursor
Set the type of pointer, PDO now supports pdo::cursor_fwdonly and pdo::cursor_fwdonly
Pdo::attr_driver_name
Returns the name of the PDO driver used
Pdo::attr_oracle_nulls
Converts the returned empty string to NULL for SQL
Pdo::attr_persistent
Get a connection that exists
Pdo::attr_statement_class
Pdo::attr_fetch_catalog_names
In the returned result set, use the custom directory name instead of the field name.
Pdo::attr_fetch_table_names
In the returned result set, use the custom table name instead of the field name.
Pdo::attr_stringify_fetches
Pdo::attr_max_column_len
Pdo::attr_default_fetch_mode
Available since PHP 5.2.0
Pdo::attr_emulate_prepares
Available since PHP 5.1.3.
Pdo::errmode_silent
No error message is reported when an error occurs, is the default value
Pdo::errmode_warning
Send a PHP e_warning message when an error occurs
Pdo::errmode_exception
Throws a pdoexception when an error occurs
Pdo::case_natural
Default display format for reply columns
Pdo::case_lower
Forced column Name lowercase
Pdo::case_upper
Force column names to uppercase
Pdo::null_natural
Pdo::null_empty_string
Pdo::null_to_string
Pdo::fetch_ori_next
Gets the next row of data in the result set, only valid if a pointer function is available
Pdo::fetch_ori_prior
Gets the previous row of data in the result set, only valid if there is a pointer function
Pdo::fetch_ori_first
Gets the first row of data in the result set, only valid if a pointer function is available
Pdo::fetch_ori_last
Gets the last row of data in the result set, only valid if a pointer function is available
Pdo::fetch_ori_abs
Gets a row of data in the result set that is valid only if there is a pointer function
Pdo::fetch_ori_rel
Gets the data for a row after the current row in the result set, only valid if there is a pointer function
Pdo::cursor_fwdonly
Create a pointer-only object that can be manipulated backwards
Pdo::cursor_scroll
Establishes a pointer manipulation object that passes the contents of the pdo::fetch_ori_* to control the result set
Pdo::err_none (String)
Set error messages when there is no error
PDO::P Aram_evt_alloc
Allocation Event
PDO::P Aram_evt_free
Deallocation Event
PDO::P aram_evt_exec_pre
Event triggered prior to execution of a prepared statement.
PDO::P aram_evt_exec_post
Event triggered subsequent to execution of a prepared statement.
PDO::P aram_evt_fetch_pre
Event triggered prior to fetching a result from a resultset.
PDO::P aram_evt_fetch_post
Event triggered subsequent to fetching a result from a resultset.
PDO::P aram_evt_normalize
Event triggered during bound parameter registration allowing the driver to normalize the parameter name.

Detailed PHP PDO library

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.