(PHP 5 >= 5.1.0, PHP 7, PECL pdo >= 0.1.0)
PDO::__construct — ����һ����ʾ���ݿ����ӵ� PDO ʵ��
$dsn
[, string $username
[, string $password
[, array $driver_options
]]] )����һ����ʾ���ӵ��������ݿ�����ݿ����� PDO ʵ����
����Դ���ƻ���� DSN���������������ӵ����ݿ����Ϣ��
ͨ����һ�� DSN �� PDO ����������������ð�š��Լ����� PDO �������������ɡ����������Ϣ�ܴ� PDO ���������ĵ��ҵ���
The dsn
����֧�����ֲ�ͬ�ķ�ʽ ����һ�����ݿ����ӣ�
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
Note:
����������� php.ini �ж����ˣ��������� .htaccess �� httpd.conf �� ��
DSN�ַ����е��û���������ijЩPDO�������˲���Ϊ��ѡ�
DSN�ַ����е����롣����ijЩPDO�������˲���Ϊ��ѡ�
һ����������������ѡ��ļ�=>ֵ���顣
�ɹ���һ��PDO����
�����ͼ���ӵ���������ݿ�ʧ�ܣ���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();
}
?>