PDO::__construct

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

PDO::__construct 锟斤拷锟斤拷一锟斤拷锟斤拷示锟斤拷锟捷匡拷锟斤拷锟接碉拷 PDO 实锟斤拷

说锟斤拷

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

锟斤拷锟斤拷一锟斤拷锟斤拷示锟斤拷锟接碉拷锟斤拷锟斤拷锟斤拷锟捷匡拷锟斤拷锟斤拷菘锟斤拷锟斤拷锟� PDO 实锟斤拷锟斤拷

锟斤拷锟斤拷

dsn

锟斤拷锟斤拷源锟斤拷锟狡伙拷锟斤拷锟� DSN锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟接碉拷锟斤拷锟捷匡拷锟斤拷锟较拷锟�

通锟斤拷锟斤拷一锟斤拷 DSN 锟斤拷 PDO 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷冒锟脚★拷锟皆硷拷锟斤拷锟斤拷 PDO 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤法锟斤拷伞锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷息锟杰达拷 PDO 锟斤拷锟斤拷锟斤拷锟斤拷锟侥碉拷锟揭碉拷锟斤拷

The dsn 锟斤拷锟斤拷支锟斤拷锟斤拷锟街诧拷同锟侥凤拷式 锟斤拷锟斤拷一锟斤拷锟斤拷锟捷匡拷锟斤拷锟接o拷

Driver invocation

dsn 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷DSN锟斤拷

URI invocation

dsn consists 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

dsn consists of a name name that maps to pdo.dsn.name in php.ini defining the DSN string.

Note:

锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟� php.ini 锟叫讹拷锟斤拷锟剿o拷锟斤拷锟斤拷锟斤拷锟斤拷 .htaccess 锟斤拷 httpd.conf 锟斤拷 锟斤拷

username

DSN锟街凤拷锟斤拷锟叫碉拷锟矫伙拷锟斤拷锟斤拷锟斤拷锟斤拷某些PDO锟斤拷锟斤拷锟斤拷锟剿诧拷锟斤拷为锟斤拷选锟筋。

password

DSN锟街凤拷锟斤拷锟叫碉拷锟斤拷锟诫。锟斤拷锟斤拷某些PDO锟斤拷锟斤拷锟斤拷锟剿诧拷锟斤拷为锟斤拷选锟筋。

driver_options

一锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷选锟斤拷募锟�=>值锟斤拷锟介。

锟斤拷锟斤拷值

锟缴癸拷锟津返伙拷一锟斤拷PDO锟斤拷锟斤拷

锟斤拷锟斤拷锟届常

锟斤拷锟斤拷锟酵硷拷锟斤拷拥锟斤拷锟斤拷锟斤拷锟斤拷锟捷匡拷失锟杰o拷锟斤拷PDO::__construct() 锟阶筹拷一锟斤拷 PDO锟届常锟斤拷PDOException锟斤拷 锟斤拷

锟斤拷锟斤拷

Example #1 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();
}

?>

Example #2 Create a PDO instance via URI invocation

The following example assumes that the file /usr/local/dbconnect exists 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 the uri: 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();
}

?>

Example #3 使锟矫憋拷锟斤拷锟斤拷锟斤拷一锟斤拷PDO实锟斤拷

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:

[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();
}

?>