PDO::__construct

(no version information, might be only in CVS)

PDO::__construct --  Creates a PDO instance representing a connection to a database

说明

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

Creates a PDO instance to represent a connection to the requested database.

参数

dsn

The Data Source Name, or DSN, contains the information required to connect to the database.

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

The dsn parameter supports three different methods of specifying the arguments required to create a database connection:

Driver invocation

dsn contains the full 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.

注: The alias must be defined in php.ini, and not .htaccess or httpd.conf

username

The user name for the DSN string. This parameter is optional for some PDO drivers.

password

The password for the DSN string. This parameter is optional for some PDO drivers.

driver_options

A key=>value array of driver-specific connection options.

返回值

Returns a PDO object on success.

异常

PDO::construct() throws a PDOException if the attempt to connect to the requested database fails.

范例

例子 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. Create a PDO instance using an alias

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
/* Connect to an ODBC database using an alias */
$dsn = 'mydb';
$user = '';
$password = '';

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

?>


add a note add a note User Contributed Notes
pirasennaNSE at gmail dot com
15-May-2006 09:34
This code will search records of a table and print it as a HTML table.
<?php

//Connecting using PDO
try {
  
$dbh = new PDO('mysql:host=localhost;dbname=test',
                      
'admin', 'password', array(PDO::ATTR_PERSISTENT => true));
      
// Note: if you want failures to be reflected as exception,
       // set this flag.
       // if this value is not set, and query fails for some reason
       // it will return a boolean variable instead of the exception.
    
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  
  
// Performing SQL query
  
$sql = 'SELECT * FROM tablename';

  
// Printing results in HTML
      
$results = $dbh->query($sql);
      
$numCols = $results->columnCount();
   echo
"<table border='1'>\n";
   echo
"\t<tr>\n";
   for(
$i = 0; $i < $numCols; ++$i) {
          
$colMeta = $results->getColumnMeta($i);
       echo
"\t\t<td>". $colMeta['name'] ."</td>\n";
       }           
   echo
"\t</tr>\n";

      
// fetch returns a resultset indexed based on parameter
       // you passed.  You can't do
       // foreach($results->fetch(PDO::FETCH_*) as $row).
      
$result = $results->fetch(PDO::FETCH_NUM);
       do {
           echo
"\t<tr>\n";
           for(
$i = 0; $i < $numCols; ++$i) {
               echo
"\t\t<td>$result[$i]</td>\n";
           }
       echo
"\t</tr>\n";
       } while(
$result = $results->fetch(PDO::FETCH_ASSOC));
   echo
"</table>\n";
}
catch(PDOException $e) {
   print
"Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>
Sasa dot Radovanovic at gmail dot com
09-Dec-2005 03:08
Since PDO can't destroyed by a call to some function e.q. close/destroy, if we'd want to get rid of it, we'd have to destroy all references to the object.

This can be quite a hassle if our database connection is passed through a layer of objects (where possible each object needs the db conn).
If we'd want to serialize the uppermost object, we would have to delete all references, so in all objects, to the db conn.
(this is necessary since PDO may not be serialized)

To implement your own ISerializeable (with __wakeup and __sleep) on each object and then restoring the db conn would be a problem,
since you'll probably only want to have the top object have knowledge about the db you're connecting to.
(so besides destroying all handles from all objects, you'd be passing also the knowledge of which db to access from the top object to the lower ones (on unserialization)).

To solve the upper problem you can write a wrapper around the access to the PDO object.
Here's a description of the wrapper i use for this.
The wrapper contains 4 methods, nl.:
<?php
__construct
(PDO $PDO, $type, $databasename, $username, $password, $host); //store the members for re-use in sleep and wakeup

/**
 * I'm to lazy to implement all PDO methods, so I use the 
 * magic method __call to handle this for me
 */
final public function __call($methodName, $arrArguments) {
  
//also check if the method exists
  
return call_user_func_array(array($this->PDOHandle , $methodName), $arrArguments);
}

//destroy our handle to PDO ($this->PDOHandle = NULL;)
//and return the array containing the members we'll want to use on wakeup
public function __sleep();

//on base of our db members, let's create a new instance of the pdo object ($this->PDOHandle = new PDO...)
public function __wakeup();
?>

This way all objects working with the database will retrieve a handle to the wrapper and only the wrapper will contain a handle to the PDO object.
So we only have to destroy the handle on one place, to ensure we can use serialization (instead of running through our object tree).