PDO Usage Learning Note _php Tutorial

Source: Internet
Author: User
Tags dsn dsn format stmt
First, the basic concept

1, pdo:php the abbreviation of the Data object. The PDO Extension Class library defines a lightweight, consistent interface for PHP that provides a data access abstraction layer so that queries and data can be executed through a consistent function, regardless of the database used.

PDO is a "database access abstraction Layer" that unifies the access interfaces of various databases.

2. Operations on any database are not performed using the PDO extension itself and must be accessed using a specific PDO driver for different database servers. such as: MYSQL (Pdo_mysql). You can view the list of PDO sections in the Phpinfo () function.

Second, the installation of PDO

1. Linux: When installing PHP, add the following flag to the Configure command:

–with-pdo-mysql=/usr/local/mysql//Where/usr/local/mysql is the MySQL installation directory

2. Windows:

Find the php.ini file under C:windows

(1) Open: Extension=php_pdo.dll

(2) Open: Extension=php_pdo_mysql.dll

Third, the use of PDO process

1. Connect to the database

(1) Creating a PDO object

(2) Setting PDO behavior Properties (setattribute ())

(3) Setting character set ($link->query (' Set names UTF8 '))

2. Send SQL statements

(1) Preparing SQL statements

(2) Perform the sending

3. View Results

Iv. Connecting the database

1. Create a PDO object:

(1) $link = new PDO (DSN, username, password, driver attribute);

1) DSN: The data source name used to define a driver that must be used and the database to be used. MySQL DSN format: ' Mysql:host=localhost;dbname=lamp30 '

2) DSN can be placed in the file, such as: ' Uri:file:///usr/local/dsn.txt '

3) Use the Try...catch statement when creating an object because an exception is automatically thrown when declaring an error on the PDO instance. Such as:

The code is as follows Copy Code

try{

$link = new PDO (' Mysql:host=localhost;dbname=lamp30 ', ' root ', ' 111111 ');

}catch (Pdoexception $e) {

echo $e->getmessage ();

Exit (' Connection database error. ');

}

2. Driver properties

(1) The necessary number of options can be made into an array (the property name as the element key, the attribute value as the element value) passed to the fourth parameter of the construction method. If you do not define a driver attribute in the constructor method, you can then use the setattribute () function of the PDO class to define the individual properties.

(2) The P501 page of the book has the Chinese interpretation of these attributes.

3. Setting character Set: $link->query (' Set names UTF8 ')

V. Send SQL statements

(1) $link->exec (): Performs additions and deletions, returns the number of rows affected, execution failure returns false or 0.

(2) $link->query (): Executes the query and returns the Pdostatement result set object.

Vi. Results of the query

1, non-query:

(1) The Return of direct $link->exec () affects the number of rows

(2) $link->lastinsertid () returns the Auto_increment number value generated by the last insert command

2, see pretreatment

Seven, pretreatment

1. Step two: Send SQL statements

The code is as follows Copy Code

$stmt = $link->prepare (' select * from user where id=:id ');

$stmt->bindparam (': Id ', $id, PDO::P aram_int);

$id = 2;

$stmt->execute ();

The Bindparam () parameter has the following 7 kinds: can not write

PDO::P aram_int

PDO::P aram_str

PDO::P Aram_bool

PDO::P aram_null

PDO::P Aram_lob: Large Object data type

PDO::P aram_stmt:pdostatement type

PDO::P aram_input_output: Data types used by stored procedures

2, the third step:

Such as:

The code is as follows Copy Code

$stmt = $link->query (' select * from user ');

(1) Fetch () method

$pdoStat->bindcolumn (1, $id); The first parameter can be an index value starting at 1

$pdoStat->bindcolumn (' name ', $name); Can also be a column name

$pdoStat->bindcolumn (' Pass ', $pass);

while ($row = $stmt->fetch (pdo::fetch_bound)) {

echo $id. ' ’;

echo $name. ' ’;

echo $pass. '
’;

}

There are six types of fetch () parameters: see Manual.

The default mode can be set using the Setfetchmode () method.

(2) Fetchall () method

The code is as follows Copy Code

$result = $stmt->fetchall ();

foreach ($result as $row) {

echo $row [' id ']. ' ’;

echo $row [' name ']. ' ’;

echo $row [' Pass ']. '
’;

}

The Fetchall () parameter is the same as fetch ().

VIII. Transaction Processing

1. Turn off autocommit (modified in driver properties)

2. Open transaction

3. COMMIT TRANSACTION/Rollback

4. Turn on auto-commit

Such as:

The code is as follows Copy Code

$link = new PDO (' mysql:host=localhost;dbname=lamp30 ');

1

$link->setattribute (Pdo::attr_autocommit, false);

2

$link->begintransaction ();

$result = $link->exec (' INSERT into user (NAME,PAA) VALUES (' Wsy ', ' 111 ') ');

3

if ($result) {

$link->commit ();

}else{

$link->rollback ();

}

4

$link->setattribute (Pdo::attr_autocommit, true);

Ix. member methods in the PDO object

1, $link->getattribute (attribute name): Gets a driver property.

2, $link->setattribute (property name, property value): Set a driver property.

1) Because ORACLE returns an empty string as a null value, and no other database has this attribute, for better compatibility $link->setattribute (Pdo::attr_oracle_nulls, Pdo::null_empty_ STRING,);

2) There are three ways to display errors: Static, warning messages, exceptions

3, $link->errorcode (): Gets the error code.

1) If the SetAttribute function is set to display the error mode as static, then nothing appears when an error occurs, you must call this function to view the error number.

4, $link->errorinfo (): Gets the error message (array).

1) If the SetAttribute function is set to display the error mode as static, then nothing appears when an error occurs, you must call this function to view the wrong information.

5, $link->lastinsertid (): Gets the last data inserted into the table primary key value (if more than one data is inserted at the same time, returns the ID of the first inserted row).

6, $link->prepare (): Sends the prepared SQL statement, returns the Pdostatement object.

7, $link->begintransaction (): Open transaction.

8, $link->commit (): Commits a transaction, executes a SQL.

9, $link->rollback (): Rolls back a transaction.

Ten, Error mode

1. Static mode:

The code is as follows Copy Code

$link->setattribute (Pdo::attr_errmode, pdo::errmode_silent)

(1) default mode, the PDO will only set the error code if the error occurs without any action.

(2) Viewing errors can be called errorcode () and ErrorInfo (), PDO and Pdostatement classes have both methods.

2. Warning Mode:

The code is as follows Copy Code

$link->setattribute (Pdo::attr_errmode, pdo::errmode_warning)

(1) This mode in addition to setting the error code, PDO will also issue a PHP traditional e_warning message.

(2) This is the way MySQL and mysqli are displayed incorrectly.

3. Abnormal mode:

The code is as follows Copy Code

$link->setattribute (Pdo::attr_errmode, pdo::errmode_exception)

(1) This mode, in addition to setting the error code, PDO will also throw a pdoexception and set its properties to reflect the error code and error message.

(2) If the exception causes the script to terminate, the transaction is automatically rolled back.

(3) PDO recommends using this mode.

Xi. Persistent connections

The code is as follows Copy Code

$link->setattribute (Pdo::attr_persistent, true);

A persistent connection is not automatically disconnected when the script is executed, and the connection cannot be closed with $link->close ().

http://www.bkjia.com/PHPjc/631647.html www.bkjia.com true http://www.bkjia.com/PHPjc/631647.html techarticle first, the basic concept of 1, pdo:php Data object abbreviation. The PDO Extension Class library defines a lightweight, consistent interface for PHP, which provides an abstraction layer of data access, so no matter ...

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