Skip navigation.
Home

Using scalability to improve your PHP applications MySQL security Part 2

Here is a quick example I threw together to extend PDO so you can use 2 seperate database connections.

This extends PDO and only connects to the database when the first query is run. This way if you never use the database connection no time is wasted trying to connect.

Basically all you do is hold off calling the __construct of PDO as this is when PDO tries to connect to the database. Every time query is run you check the value of $this->connected and if the class has not connected yet you then do a $this->__construct which connects to the db and set $this->connected = 1 so you don't keep connecting over and over.

Since you never got hold of the object returned by the __construct you have to call query directly using parent::query so the PDO object can properly reference the database its connected to.

You could do a $this->dbobject = $this->__construct and handle your querys by doing $this->dbobject->query() but using parent::query just seems a bit cleaner.

<?php
$dsn = "mysql:dbname=123;host=localhost";
$dbuser = "123";
$dbpass = "123";

class PDO_Dynamic extends PDO {
private $dsn;
private $dbuser;
private $dbpass;
private $connected = 0;
function PDO_Dynamic($dsn, $dbuser, $dbpass) {
$this->dsn = $dsn;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
}

function query($string) {
if(!$this->connected) {
try {
$this->__construct($this->dsn, $this->dbuser, $this->dbpass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
return -1;
}
$this->connected = 1;
}
return parent::query($string);
}

}

$db_read = new PDO_Dynamic($dsn, $dbuser, $dbpass);
$db_write = new PDO_Dynamic($dsn, $dbuser, $dbpass);

$result = $db_read->query('SELECT * FROM testing');
$rows = $result->fetchAll();
print_r($rows);
$result = $db_write->query('SELECT * FROM testing');
$rows = $result->fetchAll();
print_r($rows);
?>