Common methods for database operation of PDO

Source: Internet
Author: User
1, let's go over the definition of PDO:

The PDO extension defines a lightweight, consistent interface for the PHP Access database , which 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 released with PHP5.1 and can be used in the PHP5.0 pecl extension and cannot be run in previous versions of PHP.

In this I marked the important place in bold.

2, database connection

PDO has a simple connection, with only 4 parameters: Data source information (DSN), user name, password, and parameter array.
Instance:


    
     $dbh = new PDO('mysql:host=localhost;port=3306;dbname=test', $user, $pass,array (PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception));?>

If a connection error occurs, the PDOException exception is thrown. The reference code is as follows:

try{    $paramsarray (                'SET NAMES \'UTF8\'' ,                PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception,        );    $dbhnew 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($sqlas$row){        // 输出结果集中的数据echo$row['pid'].'
'; echo$row['pname'].'
';}

4, perform the update

$sql'insert into project_list(pname)values(\'tianxin\')';$rows$dbh->exec($sql);echo'更新了'.$rows.'行
';echo"最终自动编号是:".$dbh->lastInsertId()."
";

The above describes the PDO for the database operation of the common methods, including the content, I hope the PHP tutorial interested in a friend helpful.

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