• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • PDO::__construct()

    (PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)

    创建一个表示数据库连接的 PDO 实例

    说明

    PDO::__construct(string $dsn[,string $username[,string $password[,array $driver_options]]])

    创建一个表示连接到请求数据库的数据库连接 PDO 实例。

    参数

    dsn

    数据源名称或叫做 DSN,包含了请求连接到数据库的信息。

    通常,一个 DSN 由 PDO 驱动名、紧随其后的冒号、以及具体 PDO 驱动的连接语法组成。更深入的信息能从PDO 具体驱动文档找到。

    The$dsn参数支持三种不同的方式创建一个数据库连接:

    Driver invocation

    $dsn包含完整的DSN。

    URI invocation

    $dsnconsists of uri: followed by a URI that defines the location of a file containing the DSN string. The URI can specify a local file or a remote URL.

    uri:file:///path/to/dsnfile

    Aliasing

    $dsnconsists of a name$namethat maps topdo.dsn.$nameinphp.inidefining the DSN string.

    Note:

    别名必须得在php.ini中定义了,不能是在.htaccesshttpd.conf中。

    username

    DSN字符串中的用户名。对于某些PDO驱动,此参数为可选项。

    password

    DSN字符串中的密码。对于某些PDO驱动,此参数为可选项。

    driver_options

    一个具体驱动的连接选项的键=>值数组。

    返回值

    成功则返回一个PDO对象。

    错误/异常

    如果试图连接到请求的数据库失败,则PDO::__construct()抛出一个 PDO异常(PDOException)。

    范例

    Create a PDO instance via driver invocation

    <?php
    /* Connect to an ODBC database using driver invocation */
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
    $user = 'dbuser';
    $password = 'dbpass';
    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    ?>
    

    Create a PDO instance via URI invocation

    The following example assumes that the file/usr/local/dbconnectexists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

    odbc:DSN=SAMPLE;UID=john;PWD=mypass
    

    The PHP script can then create a database connection by simply passing theuri:parameter and pointing to the file URI:

    <?php
    /* Connect to an ODBC database using driver invocation */
    $dsn = 'uri:file:///usr/local/dbconnect';
    $user = '';
    $password = '';
    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    ?>
    

    使用别名创建一个PDO实例

    The following example assumes thatphp.inicontains the following entry to enable a connection to a MySQL database using only the aliasmydb:

    [PDO]
    pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
    <?php
    /*  使用别名连接到一个ODBC数据库  */
    $dsn = 'mydb';
    $user = '';
    $password = '';
    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }
    ?>
    
    To get UTF-8 charset you can specify that in the DSN.
    $link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");
    I'd like to point out that in PHP 7.0 in the dsn parameter you can't use 'host=localhost' to solve this you can use 'host=127.0.0.1' instead.
    To connect throught unix socket you need to use 
    <?php
    $dsn = 'mysql:dbname=testdb;unix_socket=/path/to/socket';
    ?>
    You musn't specify host when using socket.
    To specify a database connection port use the following DSN string
    <?php
    $dsn = 'mysql:dbname=testdb;host=127.0.0.1;port=3333';
    ?>
    
    If you use the UTF-8 encoding, you have to use the fourth parameter :
    <?php
    $db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
    ?>
    
    Sqlite:
    <?php
    try{   
      $pdo = new PDO('sqlite:example.db');
    }catch (PDOException $e){
       die ('DB Error');
    }
    ?>
    If 'example.db' does not exist, no exception is thrown but the file 'example.db' is created.
    Although not explicitly stated, parameters in the PDO $dsn string may be case-sensitive on some platforms or drivers. 
    <?php
    // The dbname will not be parsed with incorrect casing:
    $pdo = new PDO("mysql:host=hostname;DBName=database", "user", "password");
    // The correct dbname is lowercase, as displayed in the manual:
    $pdo = new PDO("mysql:host=hostname;dbname=database", "user", "password");
    ?>
    
    You will get a fatal error if you don't catch the exception threw by PDO when it fails to connect to the database server like this.
    Fatal error: in xxx.php on line xx
    This error neither can be handled by error handlers nor can it be erased by the @ sign, which can make your script uncontrollable.
    <?php
      $db = new pdo('mysql:host=127.0.0.1;port=3306;dbname=mysql;charset=utf8','user','password',array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      ));
    ?>
    You should always try ... catch ... 
    <?php
      try{
      $db = new pdo('mysql:host=127.0.0.1;port=3306;dbname=mysql;charset=utf8','user','password',array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      ));
      }catch(PDOException $pe){
        echo $pe->getMessage();
      }  
    ?>
    
    For IBM i / iSeries / AS400 DB2 connections, you can specify system naming and library lists for php_pdo modules > 1.3.3-sg2
    <?php
      $pdo = new PDO(
       'ibm:' . $host,
       $user,
       $password,
       array(
        PDO::I5_ATTR_DBC_SYS_NAMING => true,
        PDO::I5_ATTR_DBC_LIBL => "QGPL QSYS"
       )
      );
    ?>
    See http://yips.idevcloud.com/wiki/index.php/XMLSERVICE/PHPPDOChangeLog
    Just to give an odbc string connection example to MSSQL:
    $odbc="odbc:Driver={SQL Server};Server=$server;Database=$database;";
    $cnx = new PDO( $odbc , $user, $password);
    $sql="SELECT field FROM Quotation_Header WHERE (field> 0)";
    foreach ($cnx->query($sql) as $row) {
      echo $row['field'] . "\n";
    }
    To connect to the database via a function use this and call the getConnection function in the class constructor.
    <?php
    class Connection{
      protected $db;
      public function Connection(){
      $conn = NULL;
        try{
          $conn = new PDO("mysql:host=localhost;dbname=dbname", "dbuser", "dbpass");
          $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          } catch(PDOException $e){
            echo 'ERROR: ' . $e->getMessage();
            }  
          $this->db = $conn;
      }
      
      public function getConnection(){
        return $this->db;
      }
    }
    ?>
    
    If you happen to create a dsn like this...
    <?php
      //wrong dsn
      $db = new PDO('mysql:database=yourdb;host=127.0.0.1', 'user', 'password');
      $stmt = $db->prepare('SELECT * FROM tbl WHERE id = :id');
      $stmt->bindParam(':id', $user_id, PDO::PARAM_INT);
      $result = $stmt->execute();
    ?>
    ... your result will be bool(false) and your $db->errorInfo() will be "0000" which isn't very helpful.
    You have to look to the $stmt->errorInfo() to see "No database selected" which is even more confusing until you realize that it's not 'database' but 'dbname' in your DSN! You would think the error about a bad DSN would be in the $db errorInfo but it is not, it's not until you try the $stmt that the error is generated.
    <?php
      //correct dsn
      $db = new PDO('mysql:dbname=yourdb;host=127.0.0.1', 'user', 'password');
    ?>
    I wasted a half hour on that one.
    The PDO connection is case-sensitive, this means that you cannot write 
    `$PDO = new PDO("MySQL:DBName=dbname;host=localhost");`
    You would have to write it 
    `$PDO = new PDO("mysql:dbname=dbname;host=localhost");`
    The difference here is that `mysql` and `dbname` is with all lower-case.
    Some IDE's like PHPStorm will show a `TYPO ERROR`, at `dbname` if it's written with lower-case only, this is just to be ignored and have been reported to PHPStorm for them to fix. (Currrent version 10.0.2)
    pdo单例模式
    <?php
    class PdoExt extends PDO{
      static protected $_instance;
      protected function __construct($dsn, $username, $password){
        return parent::__construct($dsn, $username, $password);
      }
      static public function getInstance($dsn, $username, $password){
        if(!isset(self::$_instance)){
          self::$_instance = new self($dsn, $username, $password);
        }
        return self::$_instance;
      }
    }
    $dsn = "mysql:host=localhost";
    $username = "root";
    $password = "root";
    $pdo = PdoExt::getInstance($dsn, $username, $password);
    $sql = "SELECT user,host FROM mysql.user WHERE user = :user";
    $statement = $pdo->prepare($sql);
    $username = 'root';
    $statement->bindParam(':user', $username);
    $statement->execute();
    $users = $statement->fetchAll(2);
    print_r($users);

    上篇:PDO::commit()

    下篇:PDO::errorCode()