Here’s an extremely basic, reusable PHP and MySQL based PDO class for easily connecting to multiple database servers simultaneously within a script without having to go through a bunch of hoopla. Tidbits have been pieced together from the following sources with a little tweaking of my own (such as the ability to have default database values or to pass them as arguments):
http://simple_pdo_implementation.onlinephpfunctions.com/
http://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access–net-12059
<?php
// Simple PDO class for connecting to MySQL DB
class sql {
public static $db = false;
// Here you can set some defaults if no arguments are supplied when calling the class
private $DBHOST = '127.0.0.1';
private $DBUSER = 'johndoe';
private $DBPASS = 'secret';
private $DBNAME = 'somedb';
private $OPTIONS = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
public function __construct($dbhost = null, $dbname = null, $dbuser = null, $dbpass = null, $options = null) {
// Any options passed as arguments here should be in array format as above
// If you wanted to set attributes after being connected, use the setPDOAttrib function
if (self::$db === false) {
$dsn = "mysql:host=" . (isset($dbhost) ? $dbhost : $this->DBHOST) . ";dbname=" . (isset($dbname) ? $dbname : $this->DBNAME);
try {
$this->db = new PDO($dsn, (isset($dbuser) ? $dbuser : $this->DBUSER), (isset($dbpass) ? $dbpass : $this->DBPASS), (isset($options) ? $options : $this->OPTIONS));
} catch (PDOException $e) {
print $e->getMessage();
}
}
}
public function setPDOAttrib(){
// Can handle multiple arguments but the parameters passed here should be
// sent as one big string wrapped in quotes and separated by commas as below
// "PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION", "PDO::blah, PDO::blarg"
foreach(func_get_args() as $arg) {
if (($this->getStatus() == "1") && (!is_null($arg))) {
try {
$this->db->setAttribute($arg);
} catch (PDOException $e) {
print $e->getMessage();
}
}
}
}
public function getStatus() {
if ($this->db === true) {
return 1;
} else {
return 0;
}
}
public function close() {
if ($this->getStatus() == "1") {
$this->db = null;
}
}
}
?>
And you can call on the class like this:
$var = new sql ("localhost", "mysqluser", "mysqlpass", "mydb");
$sth = $var->db->prepare(
"SELECT
*
FROM
`sometable`
WHERE
`someid` = ?
AND
`somefield` = ?
");
$sth->execute( array ('2402', 'candyland') );
while( $r = $sth->fetchAll() ) {
echo $r;
}
Or to fetch an associative array you can use:
while($r = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "$r[someid]</br>";
echo "$r[somefield]</br>";
}
Last but not least, close your connection by doing this:
$var->close();
