PHP PDO function Library usage detailed

Source: Internet
Author: User
Tags dsn
    1. Pdo->begintransaction ()-Indicates the rollback start point
    2. Pdo->commit ()-Indicates the rollback end point and executes the SQL
    3. Pdo->__construct ()-Create an instance of the PDO link database
    4. Pdo->errorcode ()-Get error code
    5. Pdo->errorinfo ()-Get the wrong information
    6. Pdo->exec ()-Processes an SQL statement and returns the number of entries affected
    7. Pdo->getattribute ()-Gets a property of a "Database connection object"
    8. Pdo->getavailabledrivers ()-Get a valid PDO drive name
    9. Pdo->lastinsertid ()-Gets the primary key value of the last piece of data written
    10. Pdo->prepare ()-Generates a "Query object"
    11. Pdo->query ()-Processes an SQL statement and returns a "Pdostatement"
    12. Pdo->quote ()-adds quotation marks to a string in a SQL
    13. Pdo->rollback ()-Perform rollback
    14. Pdo->setattribute ()-Set properties for a database connection object
Copy Code

Second, pdostatement

  1. Pdostatement->bindcolumn ()-bind a column to a PHP variable
  2. Pdostatement->bindparam ()-binds a parameter to the specified variable name
  3. Pdostatement->bindvalue ()-binds a value to a parameter
  4. Pdostatement->closecursor ()-closes the cursor, enabling the statement to be executed again.
  5. Pdostatement->columncount ()-returns The number of columns in the result set
  6. Pdostatement->errorcode ()-fetch the SQLSTATE associated with the last operation on the statement handle
  7. Pdostatement->errorinfo ()-fetch extended error information associated with the last operation on the statement handle
  8. Pdostatement->execute ()-executes a prepared statement
  9. Pdostatement->fetch ()-fetches the next row from a result set
  10. Pdostatement->fetchall ()-returns An array containing all of the result set rows
  11. Pdostatement->fetchcolumn ()-returns a single column from the next row of a result set
  12. Pdostatement->fetchobject ()-fetches the next row and returns it as an object.
  13. Pdostatement->getattribute ()-retrieve a statement attribute
  14. Pdostatement->getcolumnmeta ()-returns metadata for a column in a result set
  15. Pdostatement->nextrowset ()-advances to the next rowset in a Multi-rowset statement handle
  16. Pdostatement->rowcount ()-returns the number of rows affected by the last SQL statement
  17. Pdostatement->setattribute ()-set a statement attribute
  18. Pdostatement->setfetchmode ()-set The default fetch mode for this statement
Copy Code

Detailed 1) database connection in PDO

    1. $dsn = ' mysql:dbname=ent;host=127.0.0.1′;
    2. $user = ' root ';
    3. $password = ' 123456′;
    4. try {
    5. $DBH = new PDO ($DSN, $user, $password, array (pdo::attr_persistent = true));
    6. $DBH->query (' Set names utf8; ');
    7. foreach ($dbh->query (' select * from Tpm_juese ') as $row) {
    8. Print_r ($row);
    9. }
    10. } catch (Pdoexception $e) {
    11. Echo ' Connection failed: '. $e->getmessage ();
    12. }
Copy Code

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.

    1. try {
    2. $DBH = new PDO (' Mysql:host=localhost;dbname=test ', ' root ', ');
    3. $DBH->query (' Set names utf8; ');
    4. $DBH->setattribute (Pdo::attr_errmode, pdo::errmode_exception);
    5. $DBH->begintransaction ();
    6. $DBH->exec (' INSERT INTO ' test ', ' table ' (' Name ', ' age ') VALUES (' Mick ', 22); ");
    7. $DBH->exec ("INSERT INTO ' test ') ' table ' (' Name ', ' age ') VALUES (' Lily ', 29);");
    8. $DBH->exec ("INSERT INTO ' test ') ' table ' (' Name ', ' age ') VALUES (' Susan ', 21);");
    9. $DBH->commit ();
    10. } catch (Exception $e) {
    11. $DBH->rollback ();
    12. echo "failed:". $e->getmessage ();
    13. }
    14. ?>
Copy Code

Now that you've established a connection through PDO, you have to figure out how PDO manages the transaction before deploying 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

    1. To modify the default error display level
    2. $DBH->setattribute (Pdo::attr_errmode, pdo::errmode_warning);
    3. ?>
copy code

List of properties: PDO::p Aram_bool represents a Boolean type PDO::p aram_null represents a null type in SQL PDO::p aram_int represents an integer type in SQL PDO::p ARAM_ STR represents a SQL Char,varchar type PDO::p Aram_lob represents a large object type PDO in sql::p aram_stmt represents a recordset type in SQL and has not been supported by PDO ::p aram_input_outputspecifies that the parameter are an inout parameter for a stored procedure. You must bitwise-or a explicit PDO::p aram_* data Type.pdo::fetch_lazy returns each row of results 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 returns only 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 simply returns the result set with the number as the underlying query Pdo::fetch_both and returns the result set with the key and number as the underlying query pdo::fetch_obj returns the result set as an object Pdo::fetch_ Bound returns the value of Pdostatement::bindparam () and Pdostatement::bindcolumn () that are bound to the variable name after the Pdo::fetch_column represents only one of the listed PDO in the result set:: Fetch_class represents the return of the result set as a class Pdo::fetch_into represents the merging of data into an existing class to return Pdo::fetch_funcpdo::fetch_grouppdo::fetch_uniquepdo:: Fetch_key_pair returns the result set in the form of the first key value, followed by the following table, Pdo::fetch_classtypepdo::fetch_serialize represents merging data into an existing class and serializing the return Pdo::fetch_ props_lateavailable since PHP 5.2.0pdo::attr_autocommit when set to True, PDO will automatically try to stop accepting delegates, start executing pdo::attr_prefetch set the data size that the application obtains in advance, not all databases Oh degrees support Pdo::attr_timeout set the value of the connection database timeout pdo::attr_ Errmode sets the mode of error handling pdo::attr_server_version read-only property, which represents the server-side database version Pdo::attr_client_version read-only property of the PDO connection, Represents the PDO-connected client PDO driver version Pdo::attr_server_info read-only property, which represents the meta information of the PDO-connected server pdo::attr_connection_statuspdo::attr_case via PDO:: Case_* the contents of a column operation 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 name of the PDO driver used Pdo::attr_oracle_nulls converts the returned empty string to SQL Nullpdo::attr_ Persistent gets an existing connection pdo::attr_statement_classpdo::attr_fetch_catalog_names in the returned result set, using 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 PHP 5.2.0pdo::attr _emulate_preparesavailable since PHP 5.1.3.pdo::errmode_silent error message is not reported when errors occur, is the default value Pdo::errmode_ Warning Send a PHP e_warning message when an error occurs pdo::errmode_exception the default display format for a pdoexceptionpdo::case_natural reply column when an error occurs PDO:: Case_lower forced column name lowercase PDO::case_upper Force column name Capital Pdo::null_naturalpdo::null_empty_stringpdo::null_to_stringpdo::fetch_ori_next gets the next row of data in the result set , only valid when there is pointer function Pdo::fetch_ori_prior get the previous row of data in the result set, only valid when there is pointer function Pdo::fetch_ori_first get the first row of data in the result set, only valid when there is pointer function Pdo::fetch_ Ori_last gets the last row of data in the result set, only valid when there is a pointer function pdo::fetch_ori_abs get a row of data in the result set, only valid when pointer function Pdo::fetch_ori_rel get the data of a row after the current row in the result set, Valid only when there is pointer function pdo::cursor_fwdonly establish a pointer manipulation object that can only be backward pdo::cursor_scroll establish a pointer action object that passes the contents of the pdo::fetch_ori_* to control the result set Pdo::err_ None (String)

Setting error messages without errors PDO::p aram_evt_allocallocation eventpdo::p aram_evt_freedeallocation eventpdo::p aram_evt_exec_ Preevent triggered prior to execution of a prepared statement.pdo::p aram_evt_exec_postevent triggered subsequent to execut Ion of a prepared statement.pdo::p Aram_evt_fetch_preevent triggered prior to fetching a result from a resultset.pdo::p Aram _evt_fetch_postevent triggered subsequent to fetching a result from a resultset.pdo::p aram_evt_normalizeevent triggered D Uring bound parameter registration allowing the driver to normalize the parameter name.

  • 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.