= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)PDO::__construct — 創(chuàng)建一個(gè)表示數(shù)據(jù)庫(kù)連接的 PDO 實(shí)例 說明PDO::__construct( string $dsn, string ">

PDO::__construct

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

PDO::__construct 創(chuàng)建一個(gè)表示數(shù)據(jù)庫(kù)連接的 PDO 實(shí)例

說明

PDO::__construct(
    string $dsn,
    string $username = ?,
    string $password = ?,
    array $driver_options = ?
)

創(chuàng)建一個(gè)表示連接到請(qǐng)求數(shù)據(jù)庫(kù)的數(shù)據(jù)庫(kù)連接 PDO 實(shí)例。

參數(shù)

dsn

數(shù)據(jù)源名稱或叫做 DSN,包含了請(qǐng)求連接到數(shù)據(jù)庫(kù)的信息。

通常,一個(gè) DSN 由 PDO 驅(qū)動(dòng)名、緊隨其后的冒號(hào)、以及具體 PDO 驅(qū)動(dòng)的連接語法組成。更深入的信息能從 PDO 具體驅(qū)動(dòng)文檔找到。

The dsn 參數(shù)支持三種不同的方式 創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)連接:

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.

注意:

別名必須得在 php.ini 中定義了,不能是在 .htaccesshttpd.conf 中 。

username

DSN字符串中的用戶名。對(duì)于某些PDO驅(qū)動(dòng),此參數(shù)為可選項(xiàng)。

password

DSN字符串中的密碼。對(duì)于某些PDO驅(qū)動(dòng),此參數(shù)為可選項(xiàng)。

driver_options

一個(gè)具體驅(qū)動(dòng)的連接選項(xiàng)的鍵=>值數(shù)組。

返回值

成功則返回一個(gè)PDO對(duì)象。

錯(cuò)誤/異常

如果試圖連接到請(qǐng)求的數(shù)據(jù)庫(kù)失敗,則PDO::__construct() 拋出一個(gè) PDO異常(PDOException) 。

范例

示例 #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();
}

?>

示例 #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();
}

?>

示例 #3 使用別名創(chuàng)建一個(gè)PDO實(shí)例

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
/*  使用別名連接到一個(gè)ODBC數(shù)據(jù)庫(kù)  */
$dsn 'mydb';
$user '';
$password '';

try {
    
$dbh = new PDO($dsn$user$password);
} catch (
PDOException $e) {
    echo 
'Connection failed: ' $e->getMessage();
}

?>