= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)PDO::__construct — 創(chuàng)建一個表示數(shù)據(jù)庫連接的 PDO 實例 說明PDO::__construct( string $dsn, string ">
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)
PDO::__construct — 創(chuàng)建一個表示數(shù)據(jù)庫連接的 PDO 實例
$dsn
,$username
= ?,$password
= ?,$driver_options
= ?創(chuàng)建一個表示連接到請求數(shù)據(jù)庫的數(shù)據(jù)庫連接 PDO 實例。
數(shù)據(jù)源名稱或叫做 DSN,包含了請求連接到數(shù)據(jù)庫的信息。
通常,一個 DSN 由 PDO 驅(qū)動名、緊隨其后的冒號、以及具體 PDO 驅(qū)動的連接語法組成。更深入的信息能從 PDO 具體驅(qū)動文檔找到。
The dsn
參數(shù)支持三種不同的方式 創(chuàng)建一個數(shù)據(jù)庫連接:
dsn
包含完整的DSN。
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
dsn
consists of a name
name
that maps to
pdo.dsn.
in php.ini
defining the DSN string.
name
注意:
別名必須得在 php.ini 中定義了,不能是在 .htaccess 或 httpd.conf 中 。
DSN字符串中的用戶名。對于某些PDO驅(qū)動,此參數(shù)為可選項。
DSN字符串中的密碼。對于某些PDO驅(qū)動,此參數(shù)為可選項。
一個具體驅(qū)動的連接選項的鍵=>值數(shù)組。
成功則返回一個PDO對象。
如果試圖連接到請求的數(shù)據(jù)庫失敗,則PDO::__construct() 拋出一個 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)建一個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數(shù)據(jù)庫 */
$dsn = 'mydb';
$user = '';
$password = '';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>