The PDO class

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

Introduction

Represents a connection between PHP and a database server.

Class synopsis

PDO {
public __construct(string $dsn, string|null $username = null, string|null $password = null, array|null $options = null)
public beginTransaction(): bool
public commit(): bool
public errorCode(): string|null
public errorInfo(): array
public exec(string $statement): int|false
public getAttribute(int $attribute): bool|int|string|array|null
public static getAvailableDrivers(): array
public inTransaction(): bool
public lastInsertId(string|null $name = null): string|false
public prepare(string $query, array $options = []): PDOStatement|false
public query(string $query, int|null $fetchMode = null): PDOStatement|false
public quote(string $string, int $type = PDO::PARAM_STR): string|false
public rollBack(): bool
public setAttribute(int $attribute, array|int $value): bool
}

Table of Contents

add a note add a note

User Contributed Notes 11 notes

up
67
Megaloman
15 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($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.
up
8
Anonymous
6 years ago
I personnaly create a new instance of PDO like this :

$dbDatas = parse_ini_file( DB_FILE );
$dbOptions = [
\PDO::ATTR_DEFAULT_FECTH_MODE => \PDO::FETCH_OBJ,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
];

$dsn = sprintf( 'mysql:dbname=%s;host=%s', $dbDatas['dbname'],
$dbDatas['host'] );

$this->cn = new \PDO( $dsn, $dbDatas['user'], $dbDatas['password'],
$dbOptions );
$this->cn->exec( 'SET CHARACTER SET UTF8' );
up
3
sinri at everstray dot com
6 years ago
For some Database Environment, such as Aliyun DRDS (Distributed Relational Database Service), cannot process preparing for SQL.
For such cases, the option `\PDO::ATTR_EMULATE_PREPARES` should be set to true. If you always got reports about "Failed to prepare SQL" while this option were set to false, you might try to turn on this option to emulate prepares for SQL.
up
10
williambarry007 at gmail dot com
12 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
7
thz at plista dot com
10 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
8
anrdaemon at freemail dot ru
15 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
4
kcleung at kcleung dot no-ip dot org
14 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
-1
ExDomino
2 years ago
Warning: the third parameter of this function is named $password and not $passwd.
up
-21
schizo_mind at hotmail dot com
15 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
-7
Ale L
5 years ago
1) Do not use your ddbb info in the same file

AND

2) DO NOT NEVER USE "All privileges user" for everything, always create an alternative user with restricted permissions (basic: SELECT, INSERT and so on)
up
-24
ronakjain2012 at gmail dot com
6 years ago
<?php

class Database
{
    private static
$_instance;
    private
$_connection;
    private
$DB_host = "localhost";
    private
$DB_user_name = "root";
    private
$DB_user_password = "";
    private
$DB_driver = "mysql";
    private
$DB_database = "test";
    public static function
init()
    {
        try {
            if (
is_null(self::$_instance) || empty(self::$_instance)) {
               
self::$_instance = new self();
                return
self::$_instance;
            }else{
                return
self::$_instance;
            }
        } catch (
Exception $e) {
            return
self::class;
        }
    }

    function
__construct()
    {
        try {
            if (
is_null($this->_connection) || empty($this->_connection)) {
               
$this->_connection = new \PDO($this->DB_driver.':host='.$this->DB_host.';dbname='.$this->DB_database, $this->DB_user_name, $this->DB_user_password);
            }
        } catch (
Exception $e) {
           
$this->_connection = $e;
        }
    }

    public function
connect()
    {
        return
$this->_connection ? $this->_connection : null;
    }
}
To Top