PDO
在线手册:中文 英文
PHP手册

The PDO class

(No version information available, might only be in SVN)

简介

Represents a connection between PHP and a database server.

类摘要

PDO {
__construct ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
bool beginTransaction ( void )
bool commit ( void )
mixed errorCode ( void )
array errorInfo ( void )
int exec ( string $statement )
mixed getAttribute ( int $attribute )
static array getAvailableDrivers ( void )
bool inTransaction ( void )
string lastInsertId ([ string $name = NULL ] )
PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
PDOStatement query ( string $statement )
string quote ( string $string [, int $parameter_type = PDO::PARAM_STR ] )
bool rollBack ( void )
bool setAttribute ( int $attribute , mixed $value )
}

Table of Contents


PDO
在线手册:中文 英文
PHP手册
PHP手册 - N: The PDO class

用户评论:

williambarry007 at gmail dot com (12-Oct-2011 09:10)

PDO and Dependency Injection

Dependency injection is good for testing.  But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.

The code below is a good way to maintain dependency injection while keeping clean and minimal model code.

<?php

class DataMapper
{
    public static
$db;
   
    public static function
init($db)
    {
       
self::$db = $db;
    }
}

class
VendorMapper extends DataMapper
{
    public static function
add($vendor)
    {
       
$st = self::$db->prepare(
           
"insert into vendors set
            first_name = :first_name,
            last_name = :last_name"
       
);
       
$st->execute(array(
           
':first_name' => $vendor->first_name,
           
':last_name' => $vendor->last_name
       
));
    }
}

// In your bootstrap
$db = new PDO(...);
DataMapper::init($db);

// In your model logic
$vendor = new Vendor('John', 'Doe');
VendorMapper::add($vendor);

?>

RockMeAmadeus (25-Aug-2010 06:44)

PDO::getAvailableDrivers is the only PDO static method so it needs a double colon. The other PDO methods are used by an object, so they should use the -> syntax.
   * PDO->beginTransaction — Initiates a transaction
    * PDO->commit — Commits a transaction
    * PDO->__construct — Creates a PDO instance representing a connection to a database
    * PDO->errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
    * PDO->errorInfo — Fetch extended error information associated with the last operation on the database handle
    * PDO->exec — Execute an SQL statement and return the number of affected rows
    * PDO->getAttribute — Retrieve a database connection attribute
    * PDO::getAvailableDrivers — Return an array of available PDO drivers
    * PDO->lastInsertId — Returns the ID of the last inserted row or sequence value
    * PDO->prepare — Prepares a statement for execution and returns a statement object
    * PDO->query — Executes an SQL statement, returning a result set as a PDOStatement object
    * PDO->quote — Quotes a string for use in a query.
    * PDO->rollBack — Rolls back a transaction
    * PDO->setAttribute — Set an attribute

kcleung at kcleung dot no-ip dot org (02-May-2010 11:47)

Here is an singleton PDO example:

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static
$link = null ;

    private static function
getLink ( ) {
        if (
self :: $link ) {
            return
self :: $link ;
        }

       
$ini = _BASE_DIR . "config.ini" ;
       
$parse = parse_ini_file ( $ini , true ) ;

       
$driver = $parse [ "db_driver" ] ;
       
$dsn = "${driver}:" ;
       
$user = $parse [ "db_user" ] ;
       
$password = $parse [ "db_password" ] ;
       
$options = $parse [ "db_options" ] ;
       
$attributes = $parse [ "db_attributes" ] ;

        foreach (
$parse [ "dsn" ] as $k => $v ) {
           
$dsn .= "${k}=${v};" ;
        }

       
self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach (
$attributes as $k => $v ) {
           
self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                ,
constant ( "PDO::{$v}" ) ) ;
        }

        return
self :: $link ;
    }

    public static function
__callStatic ( $name, $args ) {
       
$callback = array ( self :: getLink ( ), $name ) ;
        return
call_user_func_array ( $callback , $args ) ;
    }
}
?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>

Megaloman (18-Feb-2009 03:03)

"And storing username/password inside class is not a very good idea for production code."

Good idea is to store database connection settings in *.ini files but you have to restrict access to them. For example this way:

my_setting.ini:
[database]
driver = mysql
host = localhost
;port = 3306
schema = db_schema
username = user
password = secret

Database connection:
<?php
class MyPDO extends PDO
{
    public function
__construct($file = 'my_setting.ini')
    {
        if (!
$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');
       
       
$dns = $settings['database']['driver'] .
       
':host=' . $settings['database']['host'] .
        ((!empty(
$settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
       
';dbname=' . $settings['database']['schema'];
       
       
parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
    }
}
?>

Database connection parameters are accessible via human readable ini file for those who screams even if they see one PHP/HTML/any_other command.

anrdaemon at freemail dot ru (22-Aug-2008 09:16)

Keep in mind, you MUST NOT use 'root' user in your applications, unless your application designed to do a database maintenance.

And storing username/password inside class is not a very good idea for production code. You would need to edit the actual working code to change settings, which is bad.

schizo_mind at hotmail dot com (28-Jul-2008 06:00)

<?php
class PDOConfig extends PDO {
   
    private
$engine;
    private
$host;
    private
$database;
    private
$user;
    private
$pass;
   
    public function
__construct(){
       
$this->engine = 'mysql';
       
$this->host = 'localhost';
       
$this->database = '';
       
$this->user = 'root';
       
$this->pass = '';
       
$dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
       
parent::__construct( $dns, $this->user, $this->pass );
    }
}
?>