Common methods for PDO database operations

Source: Internet
Author: User
: This article mainly introduces common methods for PDO database operations. if you are interested in the PHP Tutorial, refer to it. 1. read the definition of PDO first:

PDOExtension to PHPAccess DatabaseDefines a lightweight and consistent interface, which provides a data access abstraction layer, so that no matter what database is used, data can be queried and retrieved through consistent functions. PDO is released with PHP5.1 and can also be used in the PECL extension of PHP5.0, and cannot run in the previous PHP version.

In this case, I marked the important areas in bold.

2. database connection

The PDO connection is simple, with only four parameters: data source information (DSN), user name, password, and parameter array.
Instance:


   'SET NAMES \'UTF8\'',PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception));?>

If a connection error occurs, PDO is thrown.ExceptionException. The reference code is as follows:

try{    $params = array (                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' ,                PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception,        );    $dbh = new PDO('mysql:host='.$mysql_server_name.';dbname='.$mysql_database, $mysql_username, $mysql_password,$params);    echo"DB Connect OK!!!".'
';}catch(PDOException $e){ echo"DB Connect Error!!!".$e->getMessage(); exit;}

3. execute the query:

$ SQL = 'SELECT pid, pname from project_list '; foreach ($ dbh-> query ($ SQL) as $ row) {// data in the output result set echo $ row ['pid'].'
'; Echo $ row ['pname'].'
';}

4. execute updates.

$ SQL = 'Insert into project_list (pname) values (\ 'tianxin \ ')'; $ rows = $ dbh-> exec ($ SQL); echo 'Updated '. $ rows. 'line
'; Echo "the final automatic number is:". $ dbh-> lastInsertId ()."
";

The above describes the common methods of PDO database operations, including the content, and hope to be helpful to friends who are interested in PHP tutorials.

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.