PHP PDO function Library detailed

Source: Internet
Author: User
Tags dsn getmessage rowcount

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 of PDO that contain three predefined classes, namely PDO, Pdostatement, and Pdoexception. First, Pdopdo-BeginTransaction ()-Indicates the rollback starting point PDO-commit ()-Indicates the rollback end point and executes the Sqlpdo-__construct ()-Create an instance of the PDO link database PDO-ErrorCode ()-Get the error code PDO-errorinfo ()-Get the wrong information PDO-exec()-Processes an SQL statement and returns the number of affected items PDO-getattribute ()-Gets the properties of a "Database connection object" PDO-getavailabledrivers ()-Get a valid PDO drive name PDO-Lastinsertid ()-Gets the primary key value of the last data written by 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-RollBack ()-Perform rollback PDO-SetAttribute ()-Set properties for a "Database connection object" Two, Pdostatementpdostatement-Bindcolumn ()-bind a column to a PHP variablepdostatement-Bindparam ()-binds a parameter to the specified variable namepdostatement-Bindvalue ()-binds a value to a parameterpdostatement->closecursor ()-closes the cursor, enabling the statement to be executed again.pdostatement->columncount ()-returns the Numberof columns in the result setpdostatement-ErrorCode ()-fetch the SQLSTATE associated with the last operation on the statement handlepdostatement-errorinfo ()-fetch extended error information associated with the last operation on the statement handlepdostatement< /c0>-Execute ()-executes a prepared statementpdostatement->fetch ()-fetches theNextrow from a result setpdostatement->fetchall ()-returns anArrayContaining all of the result set rowspdostatement->fetchcolumn ()-returns a single column from theNextrow of a result setpdostatement->fetchobject ()-fetches theNextRow and returns it asAnObject.pdostatement-getattribute ()-retrieve a statement attributepdostatement->getcolumnmeta ()-returns metadata fora column in a result setpdostatement->nextrowset ()-advances to theNextRowset in a multi-Rowset Statement Handlepdostatement->rowcount ()-returns the Numberof rows affected by the last SQL statementpdostatement-SetAttribute ()-set a statement attributepdostatement->setfetchmode ()-set thedefaultFetch mode forThis statementpdo 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 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 of PDO that contain three predefined classes, namely PDO, Pdostatement, and Pdoexception. First, Pdopdo-BeginTransaction ()-Indicates the rollback starting point PDO-commit ()-Indicates the rollback end point and executes the Sqlpdo-RollBack ()-Perform rollback PDO-__construct ()-Create an instance of the PDO link database PDO-ErrorCode ()-Get the error code PDO-errorinfo ()-Get the wrong information PDO-exec()-Processes an SQL statement and returns the number of affected items PDO-getattribute ()-Gets the properties of a "Database connection object" PDO-getavailabledrivers ()-Get a valid PDO drive name PDO-Lastinsertid ()-Gets the primary key value of the last data written by 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 ()-setting properties for a "Database connection object" detailed 1) Database connections in PDO$dsn=MySQL:d bname=ent;host=127.0.0.1;$user= ' Root '; $password = ' 123456′;try {$dbh = new PDO ($DSN, $user, $password, array (pdo::attr_persistent = true)); $DBH->qu Ery (' 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. A persistent connection is not closed at the end of the script, but 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. 2) the transaction pdo->begintransaction (), Pdo->commit (), Pdo->rollback () in PDO are used together in support of rollback functionality. 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. <?phptry {$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, (now briefly:) They offer 4 main features: Atomicity, consistency, independence, and persistence (atomicity, consistency,isolation and Durability,acid) in layman's words, 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 use PDOThe->begintransaction () method creates a. 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 use Pdo->commit () or pdo->RollBack () ends it, 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, pdostatementpdostatement-Bindcolumn ()-bind a column to a PHP variablepdostatement-Bindparam ()-binds a parameter to the specified variable namepdostatement-Bindvalue ()-binds a value to a parameterpdostatement->closecursor ()-closes the cursor, enabling the statement to be executed again.pdostatement->columncount ()-returns the Numberof columns in the result setpdostatement-ErrorCode ()-fetch the SQLSTATE associated with the last operation on the statement handlepdostatement-errorinfo ()-fetch extended error information associated with the last operation on the statement handlepdostatement< /c6>-Execute ()-executes a prepared statementpdostatement->fetch ()-fetches theNextrow from a result setpdostatement->fetchall ()-returns anArrayContaining all of the result set rowspdostatement->fetchcolumn ()-returns a single column from theNextrow of a result setpdostatement->fetchobject ()-fetches theNextRow and returns it asAnObject.pdostatement-getattribute ()-retrieve a statement attributepdostatement->getcolumnmeta ()-returns metadata fora column in a result setpdostatement->nextrowset ()-advances to theNextRowset in a multi-Rowset Statement Handlepdostatement->rowcount ()-returns the Numberof rows affected by the last SQL statementpdostatement-SetAttribute ()-set a statement attributepdostatement->setfetchmode ()-set thedefaultFetch mode forThis Statement III, PDOEXCEPTIONPDO provides 3 different error handling strategies. 1. PDO::Errmode_silent This is the default mode used. PDO will set a simple error code on the statement and database objects, you can use PDOThe->errorcode () and Pdo->errorinfo () methods Check for errors, and if the error is caused by a call to the statement object, you can use Pdostatement->errorcode () on that object or pdostatement->The errorinfo () method gets 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 as an addition to the Setup error code, PDO will emit a traditional e_warning message. 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 Chapter PDO using SQL-based-92 SQLSTATE Error code string; 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->The errorinfo () method, which can return an error description string that contains the SQLSTATE code name, a specific database-driven error code, and a specific database driver. <?PHP//to modify the default error display level$DBH->setattribute (Pdo::attr_errmode, PDO::errmode_warning);?>attribute list: PDO::Param_bool Represents a Boolean type PDO::Param_null represents a null type in SQL PDO::param_int represents an integer type of PDO in SQL::PARAM_STR represents a SQL Char,varchar type PDO in SQL::Param_lob represents a large object type PDO in SQL::param_stmt represents a recordset type in SQL and has not been supported by PDO::Param_input_outputspecifies that the parameter was an INOUT parameter forA stored procedure. You must bitwise-or the value with an explicit PDO::P aram_* data type.PDO::Fetch_lazy returns the PDO for each row of results as an object::FETCH_ASSOC only returns a result set with a key value as the underlying query, and 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 returns the PDO as an array::Fetch_num only returns the 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 the result set as an object PDO::Fetch_bound will pdostatement:: Bindparam () and pdostatement::Bindcolumn () returns PDO when the value that is bound is assigned as a variable name::Fetch_column indicates that only one column of PDO in the result set is returned::Fetch_class indicates that the result set is returned as a class PDO::Fetch_into means that data is merged into an existing class to return PDO::Fetch_funcpdo::Fetch_grouppdo::Fetch_uniquepdo::Fetch_key_pair Returns the result set as the first key value in the following table, followed by the following table, PDO::Fetch_classtypepdo::fetch_serialize means merging data into an existing class and serializing the returned PDO::fetch_props_lateavailable since PHP5.2.0PDO::Attr_autocommit When set to True, PDO will automatically try to stop accepting delegates and start executing PDO::Attr_prefetch Set the size of the data that the application obtains in advance, not all databases Oh degree support PDO::attr_timeout Setting 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 PDO connection PDO::Attr_client_version Read-only property that represents the PDO-connected client PDO driver version PDO::Attr_server_info Read-only property, which represents the meta information PDO for the server on which PDO is connected::Attr_connection_statuspdo::Attr_case via PDO:: case_*The contents of the column are manipulated in the form of the PDO::Attr_cursor_name Gets or sets the name of the pointer PDO::Attr_cursor Sets the type of pointer, PDO now supports PDO:: Cursor_fwdonly and PDO::Cursor_fwdonlypdo::Attr_driver_name returns the PDO driver using the name PDO::Attr_oracle_nulls Converts the returned empty string to the nullpdo of SQL::Attr_persistent get an existing connection PDO::Attr_statement_classpdo::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_fetchespdo::Attr_max_column_lenpdo::attr_default_fetch_modeavailable since PHP5.2.0PDO::attr_emulate_preparesavailable since PHP5.1.3.PDO::errmode_silent error message is not reported when errors occur, is the default PDO::errmode_warning An error occurs when issuing a PHP e_warning information PDO::Errmode_exception throws a pdoexceptionpdo when an error occurs::case_natural default display format for reply columns PDO::case_lower Mandatory column name lowercase PDO::case_upper Mandatory Column name uppercase PDO::Null_naturalpdo::Null_empty_stringpdo::Null_to_stringpdo::Fetch_ori_next Gets the next row of data in the result set, only if the PDO is active with the pointer function::Fetch_ori_prior Gets the previous row of data in the result set, only if the PDO is active with the pointer function::Fetch_ori_first Gets the first row of data in the result set, only the PDO when the pointer function is available::Fetch_ori_last Gets the last row of data in the result set, only valid PDO if pointer function is available::Fetch_ori_abs gets a row of data in the result set, only valid PDO if pointer function is available::Fetch_ori_rel Gets the data for a row after the current row in the result set, only valid when the pointer function is available PDO::cursor_fwdonly Setting up a pointer-only operation object PDO::Cursor_scroll set up a pointer manipulation object to pass PDO:: fetch_ori_*to control the result set PDO:: Err_none (string) Set the error message without error PDO::param_evt_allocallocation Eventpdo::param_evt_freedeallocation Eventpdo::Param_evt_exec_preevent triggered prior to execution of a prepared statement.PDO::Param_evt_exec_postevent triggered subsequent to execution of a prepared statement.PDO::Param_evt_fetch_preevent triggered prior to fetching a result from a resultset.PDO::Param_evt_fetch_postevent triggered subsequent to fetching a result from a resultset.PDO::param_evt_normalizeevent triggered during bound parameter registration allowing the driver to normalize the parameter Name.

PHP PDO function Library detailed

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.