PDO 类

PDO 类

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

简介

代表 PHP 和数据库服务之间的一个连接

类摘要

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

Table of Contents

add a note add a note

User Contributed Notes 8 notes

up
30
Megaloman  ¶
7 years ago
"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($fileTRUE)) 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.
up
7
anrdaemon at freemail dot ru  ¶
8 years ago
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.
up
3
thz at plista dot com  ¶
3 years ago
Starting with PHP 5.4 you are unable to use persistent connections when you have your own database class derived from the native PDO class. If your code uses this combination, you will encounter segmentation faults during the cleanup of the PHP process.
You can still use _either_ a derived PDO class _or_ persistent connections.

For more information, please see this bug report: https://bugs.php.net/bug.php?id=63176
up
1
rumsg at mail dot ru  ¶
1 year ago
$DB = new PDO('mysql:host=127.0.0.1;port=3306;dbname=anexis_new;charset=UTF8;','root','password', array(PDO::ATTR_PERSISTENT=>true));
$DB->query("SET NAMES utf8;");
up
3
kcleung at kcleung dot no-ip dot org  ¶
6 years ago
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 ( ) ;
?>
up
2
williambarry007 at gmail dot com  ¶
5 years ago
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);

?>
up
3
schizo_mind at hotmail dot com  ¶
8 years ago
<?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 ); 
    } 

?>
up
-9
sideshowAnthony at googlemail dot com  ¶
1 year ago
Here is a cheeky PDO helper class to get you started . . .

define('DB_MAIN', 'localhost|user1|pa55word|db1');

// Connect to database db1
$db = new my_db(DB_MAIN);

// Request "SELECT * FROM table1 WHERE a=16 AND b=22"
// Get an array of stdClass's
$rows = $db->fetchAll('SELECT * FROM table1 WHERE a=? AND b=?', 16, 22);

class my_db{

    private static $databases;
    private $connection;

    public function __construct($connDetails){
        if(!is_object(self::$databases[$connDetails])){
            list($host, $user, $pass, $dbname) = explode('|', $connDetails);
            $dsn = "mysql:host=$host;dbname=$dbname";
            self::$databases[$connDetails] = new PDO($dsn, $user, $pass);
        }
        $this->connection = self::$databases[$connDetails];
    }
    
    public function fetchAll($sql){
        $args = func_get_args();
        array_shift($args);
        $statement = $this->connection->prepare($sql);        
        $statement->execute($args);
         return $statement->fetchAll(PDO::FETCH_OBJ);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值