PHP PDO operations database, PHPPDO database _php Tutorial

Source: Internet
Author: User
Tags dsn prefetch

PHP PDO operations database, PHPPDO database


Pod extension is added in PHP5, which provides PHP built-in class PDO to access the database, different databases use the same method name, to solve the problem of non-uniform database connection.

features of PDO:

Performance. PDO has learned from the outset the successes and failures of existing database extensions. Because PDO's code is brand new, we have the opportunity to start designing performance again to take advantage of the latest features of PHP 5.
Ability. PDO is designed to provide the basis for common database functionality while providing easy access to the unique features of the RDBMS.
Simple. PDO is designed to make it easy to use your database. The API does not force you into your code, and it clearly shows the process of each function call.
The runtime is extensible. The PDO extension is modular, allowing you to load drivers at run time for your database backend without having to recompile or reinstall the entire PHP program. For example, the PDO_OCI extension implements the Oracle database API instead of the PDO extension. There are also drivers for MySQL, PostgreSQL, ODBC, and Firebird, and more drivers are still being developed.

  

PDO Installation

You can use the PHP phpinfo () function to see if the PDO extension is installed.

1. Installing PDO on the Unix/linux system

On UNIX or Linux you need to add the following extensions:

Extension=PDO. So

  2. Installing PDO in Windows

PDO and all major drivers are released as shared extensions with PHP, and to activate them simply edit the php.ini file and add the following extensions:

Extension=php_pdo. DLL

In addition, there are a variety of database extensions that correspond to the following:

;Extension=Php_pdo_firebird.Dll;Extension=Php_pdo_informix.Dll;Extension=Php_pdo_mssql.Dll;Extension=php_pdo_mysql.; Extension=php_pdo_oci.; Extension=php_pdo_oci8.; Extension=php_pdo_odbc.; Extension=php_pdo_pgsql.; Extension=php_pdo_sqlite.                 

Open the php.ini to remove the semicolon from the front of all the lines above.
After setting up these configurations, we need to restart the PHP or Web server.

Let's take MySQL for example to use PDO:

 
  php$dbms= ' MySQL ';     Database type $host= ' localhost '; Database host name $dbname= ' test ';    The database used $user= ' root ';      Database connection user name $pass= ";          The corresponding password $dsn= "$dbms: host= $host;d bname= $dbName"; try {    $dbh = new PDO ($DSN, $user, $pass);//Initialize a PDO object    echo "Connection successful
"; /* You can also perform a search operation foreach ($dbh->query (' SELECT * from FOO ') as $row) { print_r ($row);//You can use Echo ($GLOBAL); To see these values } * /$DBH =null;} catch (Pdoexception $e) {die ("error!:". $e->getmessage (). "
");} Default this is not a long connection, if you need a long database connection, you need to add one last parameter: Array (pdo::attr_persistent = True) to this: $db = new PDO ($DSN, $user, $pass, Array ( Pdo::attr_persistent = True));? >

  Let's take a look at PDO's detailed introduction:

1. Predefined constants:

PDO::P aram_bool (integer) Represents a Boolean data type.
PDO::P aram_null (integer) Represents a NULL data type in SQL.
PDO::P aram_int (integer) Represents an integral type in SQL.
PDO::P aram_str (integer) Represents a CHAR, VARCHAR, or other string type in SQL.
PDO::P aram_lob (integer) Represents a large object data type in SQL.
PDO::P aram_stmt (integer) Represents a record set type. Currently not supported by any driver.
PDO::P aram_input_output (integer) Specifies that the parameter is a INOUT parameter for a stored procedure. You must use a definite PDO::P aram_* data type is bitwise OR with this value.
Pdo::fetch_lazy (integer) Specifies the fetch method that returns each row in the result set as an object with the name of the variable that corresponds to the column name. Pdo::fetch_lazy creates the object variable name to access. is not valid in Pdostatement::fetchall ().
PDO::FETCH_ASSOC (integer) Specifies the fetch method that returns each row in the corresponding result set as an array indexed by the column name. If the result set contains more than one column with the same name, PDO::FETCH_ASSOC returns only one value per column name.
Pdo::fetch_named (integer) Specifies the fetch method that returns each row in the corresponding result set as an array indexed by the column name. If the result set contains more than one column with the same name, PDO::FETCH_ASSOC returns an array containing the values for each column name.
Pdo::fetch_num (integer) Specifies the fetch method, which returns each row in the corresponding result set as an array indexed by the column number, starting at column No. 0.
Pdo::fetch_both (integer) Specifies the fetch method, which returns each row in the corresponding result set as an array indexed by the column and column names, starting at column No. 0.
Pdo::fetch_obj (integer) Specifies the fetch method that returns each row in the result set as an object that corresponds to the column name of the property name.
Pdo::fetch_bound (integer) Specifies the fetch method, which returns TRUE and assigns the column values in the result set to PHP variables bound by the Pdostatement::bindparam () or Pdostatement::bindcolumn () method.
Pdo::fetch_column (integer) Specifies the fetch method that returns the column you want from the next row in the result set.
Pdo::fetch_class (integer) Specifies the fetch method, returns a new instance of the requested class, and maps the column to the corresponding property name in the class.

Note: If the property does not exist in the requested class, call the __set () Magic method

Pdo::fetch_into (integer) Specifies the fetch method, updates an existing instance of a request class, and maps the column to the corresponding property name in the class.
Pdo::fetch_func (integer) Allows data to be processed completely in a custom manner in the run. (only valid in Pdostatement::fetchall ().)
Pdo::fetch_group (integer) is returned according to the value grouping. Usually used in conjunction with Pdo::fetch_column or Pdo::fetch_key_pair.
Pdo::fetch_unique (integer) Only unique values are taken.
Pdo::fetch_key_pair (integer) Gets a result set of two columns into an array, where the first column is the key name, and the second column is the value. Available from PHP 5.2.3.
Pdo::fetch_classtype (integer) Determines the class name based on the value of the first column.
Pdo::fetch_serialize (integer) Similar to Pdo::fetch_into, but represents an object as a serialized string. Available from PHP 5.1.0. Starting with PHP 5.3.0, if you set this flag, the constructor of the class will never be called.
Pdo::fetch_props_late (integer) The constructor is called before the property is set. Available from PHP 5.2.0.
Pdo::attr_autocommit (integer) If this value is FALSE, PDO attempts to disable autocommit so that the database connection begins a transaction.
Pdo::attr_prefetch (integer) Set the prefetch size to balance speed and memory usage for your app. Not all database/driver combinations support setting prefetch size. A larger prefetch size results in increased performance while also consuming more memory.
Pdo::attr_timeout (integer) Sets the time-out number of seconds to connect to the database.
Pdo::attr_errmode (integer) For more information about this property, see the Error and Error handling section.
Pdo::attr_server_version (integer) This is a read-only property; Returns the version information for the database service to which PDO is connected.
Pdo::attr_client_version (integer) This is a read-only property; Returns the version information for the client library used by the PDO driver.
Pdo::attr_server_info (integer) This is a read-only property. Returns some meta information about the database service that PDO is connected to.
Pdo::attr_connection_status (integer)
Pdo::attr_case (integer) Enforces the column name to the specified case with a constant similar to pdo::case_*.
Pdo::attr_cursor_name (integer) Gets or sets the name of the use cursor. Useful when using scrollable cursors and locating updates.
Pdo::attr_cursor (integer) Select the cursor type. PDO currently supports pdo::cursor_fwdonly and Pdo::cursor_scroll. Typically pdo::cursor_fwdonly, unless you do need a scrollable cursor.
Pdo::attr_driver_name (String) Returns the drive name.

Examples of using pdo::attr_driver_name:

   
     GetAttribute (pdo::attr_driver_name) = = ' MySQL ') {  echo ' Running on MySQL; Doing something MySQL specific here\n ";}? >
Pdo::attr_oracle_nulls (integer) Converts an empty string to NULL in SQL when fetching data.
Pdo::attr_persistent (integer) Request a persistent connection rather than create a new one. For more information about this property, see Connection and connection management.
Pdo::attr_statement_class (integer)
Pdo::attr_fetch_catalog_names (integer) Adds the included directory name to each column name in the result set. The directory name and column name are separated by a decimal point (.). This property is supported at the drive level, so some drivers may not support this property.
Pdo::attr_fetch_table_names (integer) Add the included table names to each column name in the result set. The table name and column name are separated by a decimal point (.). This property is supported at the drive level, so some drivers may not support this property.
Pdo::attr_stringify_fetches (integer)
Pdo::attr_max_column_len (integer)
Pdo::attr_default_fetch_mode (integer) Available from PHP 5.2.0.
Pdo::attr_emulate_prepares (integer) Available from PHP 5.1.3.
Pdo::errmode_silent (integer) If an error occurs, no error or exception is displayed. You want the developer to explicitly check for errors. This is the default mode. For more information about this property, see Error and error handling.
Pdo::errmode_warning (integer) If an error occurs, a PHP e_warning message is displayed. For more information about this property, see Error and error handling.
Pdo::errmode_exception (integer) If an error occurs, a Pdoexception exception is thrown. For more information about this property, see Error and error handling.
Pdo::case_natural (integer) Retains the name of the column returned by the database driver.
Pdo::case_lower (integer) Enforces the column name lowercase.
Pdo::case_upper (integer) Force column names to uppercase.
Pdo::null_natural (integer)
Pdo::null_empty_string (integer)
Pdo::null_to_string (integer)
Pdo::fetch_ori_next (integer) Gets the next row in the result set. Valid only for scrollable cursors.
Pdo::fetch_ori_prior (integer) Gets the previous row in the result set. Valid only for scrollable cursors.
Pdo::fetch_ori_first (integer) Gets the first row in the result set. Valid only for scrollable cursors.
Pdo::fetch_ori_last (integer) Gets the last row in the result set. Valid only for scrollable cursors.
Pdo::fetch_ori_abs (integer) Gets the required rows from the result set based on the line number. Valid only for scrollable cursors.
Pdo::fetch_ori_rel (integer) Gets the desired row from the result set based on the relative position of the current cursor position. Valid only for scrollable cursors.
Pdo::cursor_fwdonly (integer) Creates a Pdostatement object that is a forward-only cursor. This is the default cursor option because this cursor is the fastest and most commonly used data access mode in PHP.
Pdo::cursor_scroll (integer) Creates a Pdostatement object for a scrollable cursor. The rows obtained in the result set are controlled by Pdo::fetch_ori_* constants.
Pdo::err_none (String) Corresponds to SQLSTATE ' 00000 ', which indicates that the SQL statement was successfully issued without error or warning. This constant is handy when using Pdo::errorcode () or Pdostatement::errorcode () to determine if an error occurs. It is often used when checking the error status codes returned by the above methods.
PDO::P aram_evt_alloc (integer) Assigning events
PDO::P aram_evt_free (integer) deallocation Events
PDO::P aram_evt_exec_pre (integer) Triggers an event before executing a preprocessing statement.
PDO::P aram_evt_exec_post (integer) Triggers an event after executing a preprocessing statement.
PDO::P aram_evt_fetch_pre (integer) Triggers an event before extracting a result from a result set.
PDO::P aram_evt_fetch_post (integer) Triggers an event after extracting a result from a result set.
PDO::P aram_evt_normalize (integer) Triggers an event when the binding parameter registration allows the driver to normalize the variable name.

2.PDO class:

    • pdo::begintransaction-Start a transaction
    • pdo::commit-Commit a transaction
    • pdo::__construct-creating a PDO instance that represents a database connection
    • Pdo::errorcode-gets the SQLSTATE associated with the last operation of the database handle
    • Pdo::errorinfo-returns the error message for the last operation of the database
    • pdo::exec-executes an SQL statement and returns the number of rows affected
    • Pdo::getattribute-retrieving the properties of a database connection
    • pdo::getavailabledrivers-returns an array of available drives
    • pdo::intransaction-check whether within a transaction
    • Pdo::lastinsertid-returns the ID or sequence value of the last inserted row
    • PDO::p repare-prepare the SQL statement to execute and return a Pdostatement object
    • pdo::query-executes the SQL statement, returning the Pdostatement object, which can be understood as a result set
    • Pdo::quote-adds quotation marks to the strings in the SQL statement.
    • pdo::rollback-rolling back a transaction
    • pdo::setattribute-Setting properties
    • Pdostatement class:
        The
        • pdostatement::bindcolumn-binds a column to a PHP variable
        • pdostatement::bindparam-binds a parameter to the specified variable name
        • pdostateme Nt::bindvalue-binds a value to a parameter
        • pdostatement::closecursor-closes the cursor so that the statement can be executed again.
        • pdostatement::columncount-Returns the number of columns in the result set
        • pdostatement::d ebugdumpparams-print a SQL preprocessing command
        • Pdosta Tement::errorcode-gets the SQLSTATE
        • pdostatement::errorinfo-associated with the last statement handle operation gets the extended error message associated with the last statement handle operation
        • Pdostatement::execute-executes a preprocessing statement
        • pdostatement::fetch-gets the next line from the result set
        • pdostatement::fetchall- Returns an array containing all the rows in the result set
        • pdostatement::fetchcolumn-returns a separate column from the next row in the result set. The
        • pdostatement::fetchobject-gets the next line and returns as an object.
        • pdostatement::getattribute-Retrieving a statement property
        • pdostatement::getcolumnmeta-Returns the metadata for a column in the result set
        • Pdostatement::nextrowset-advance to the next rowset in a multi-rowset statement handle
        • pdostatement::rowcount-returns the number of rows affected by the previous SQL statement
        • pdostatement::setattribute-set a statement property
        • pdostatement::setfetchmode-to set the default fetch mode for the statement.

http://www.bkjia.com/PHPjc/1125063.html www.bkjia.com true http://www.bkjia.com/PHPjc/1125063.html techarticle PHP PDO operations database, phppdo database pod extension is added in the PHP5, the extension provides PHP built-in class PDO to access the database, different databases using the same method name, solve the number ...

  • Related Article

    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.