PDO: Connection timed out when database is offline - php

I have a website that makes a connection to an external database with PDO.
All right, all works.
The only problem is when the database goes offline. I refresh the website, the browser load the first query that finds but it takes 30+ seconds to load it and when finish the page stop to load (because there is an exit(); function when the connection fails) with this error:
SQLSTATE[HY000] [2002] Connection timed out
I want the website accessible normally when the database goes offline, because is a routine that it goes offline but there's this problem of the Connection timed out and of the page that takes 30+ seconds to load.
How can I resolve this problem?
This is how I do a connection and a query:
class.db.php
<?php
class db
{
private $db = NULL;
private $host = NULL;
private $user = NULL;
private $password = NULL;
private $port = NULL;
public function __construct($host, $user, $password, $port) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->port = $port;
}
private function initDb() {
if($this->db == NULL) {
try {
$this->db = new PDO('mysql:port='.$this->port.';host='.$this->host, $this->user, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $error) {
echo '<b>An error occured!</b><br />' . $error->getMessage();
exit();
}
}
}
public function query($array) {
$this->initDb();
$sql = $array['sql'];
$par = (isset($array['par'])) ? $array['par'] : array();
$ret = (isset($array['ret'])) ? $array['ret'] : 'res';
$obj = $this->db->prepare($sql);
$result = $obj->execute($par);
if (!$result) exit("Errore Query");
switch ($ret) {
case 'fetch-assoc':
return $obj->fetch(PDO::FETCH_ASSOC);
break;
case 'fetch-all':
return $obj->fetchAll(PDO::FETCH_ASSOC);
break;
case 'fetch-column':
return $obj->fetchColumn();
break;
case 'result':
return $result;
break;
default:
return $result;
break;
}
}
public function __destruct() {
$this->db = NULL;
}
}
Usage (how I run a query)
require_once ROOT . 'include/class.db.php';
$config['db']['servername'] = ""; // Database IP
$config['db']['username'] = ""; // Database Username
$config['db']['password'] = ""; // Database Password
$config['db']['port'] = 3306; // Database Port
$db = new db($config['db']['servername'], $config['db']['username'], $config['db']['password'], $config['db']['port']);
// Example of a query
$data = $db->query(array(
'sql' => "SELECT count(*) FROM player.player WHERE DATE_SUB(NOW(), INTERVAL 1 DAY) < player.last_play",
'ret' => 'fetch-column'
));
echo $data;
Thanks for the help.

You could set the timeout attribute:
private function initDb() {
if($this->db == NULL) {
try {
$this->db = new PDO('mysql:port='.$this->port.';host='.$this->host, $this->user, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_TIMEOUT, 5); //Add this.
}
catch (PDOException $error) {
echo '<b>An error occured!</b><br />' . $error->getMessage();
exit();
}
}
}
This would make the query time out after 5 seconds instead of the 30 seconds you describe in your question. Please note that the underlying mysql engine has to support this as not all support it.

If you want your website to be accessible, even when you can't access the database, I see two solutions : caching the results of the query ; or caching the entire page.

Related

i have sql custom execution method, but there are found error unbuffered query

i have a class which has custom query execution. Then it shown some error if after i execute that.
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I have search out my problem answer but, almost of them recommend me to put $stmt->closeCursor() in my code, but i have done with it and still get error. The error shown is same with error above. Below is my DBClassification class. Please help me. Thanks :)
<?php
class DBClassification
{
public $db = null;
public $host = "localhost";
public $user = "root";
private $pass = "";
public $path = __DIR__ . "\\";
public $prefixFilename = "klasifikasi_";
public $dbexception = [];
public $stmt;
public function setHost($host){
$this->host = $host;
}
public function setUser($user){
$this->user = $user;
}
public function setPass($pass){
$this->pass = $pass;
}
public function setPath($path)
{
if (!is_dir($path)) die ("Directory \$path is not correct!\n$path");
$lastchar = substr($path, -1);
if ($lastchar != "/" && $lastchar != "\\") $path = $path . "/";
if (strpos($path, '/') !== false) $path = str_replace("/","\\",$path);
$this->path = $path . $this->host . "\\"; // setting path to the generated output file
}
public function setPrefixFilename($prefixFilename){
$this->prefixFilename = $prefixFilename;
}
public function setDBException($dbexception=[]){
$this->dbexception = $dbexception;
}
public function init($host,$user,$pass,$path,$prefixFilename,$dbexception=[])
{
if (!$dbexception) $dbexception = ["information_schema","mysql","performance_schema","phpmyadmin","sys"];
$this->setHost($host);
$this->setUser($user);
$this->setPass($pass);
$this->setPath($path);
$this->setPrefixFilename($prefixFilename);
$this->setDBException($dbexception);
$this->openConnection();
}
// Establishing Connection to mysql database on specified host
public function openConnection(){
try {
$db = new PDO("mysql:host=".$this->host, $this->user, $this->pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db = $db;
return true;
} catch (PDOException $e) {
die("Error!: " . $e->getMessage());
}
return false;
}
public function run(){
try {
$databases = $this->stmtExec("SHOW DATABASES",true);
foreach($databases as $database): // execute each database
$dbname = $database['Database']; // database name
if(!in_array($dbname,$this->dbexception)): // prevent clasifying dbname which contain in dbexception
echo "USE $dbname\n";
$this->stmtExec("USE $dbname");
$tables = $this->stmtExec("SHOW TABLES",true);
endif; // if(!in_array($dbname,$dbexception)):
endforeach; // foreach($databases as $database):
} catch (Exception $e) {
echo "Something wrong, failed to clasify each database in host " . $this->host . "\n";
die("Error!: ".$e->getMessage());
}
}
public function stmtExec($sql,$fetch=false)
{
try {
$this->stmt = $this->db->prepare($sql);
if ($fetch) {
if ($this->stmt->execute()) $return = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$return = $this->stmt->execute();
}
$this->stmt->closeCursor();
} catch (PDOException $e) {
$errormsg = "db Error: ". $this->stmt->queryString . PHP_EOL . $e->getMessage();
$queryFilename = $this->path . "error.txt";
file_put_contents($queryFilename, $errormsg);
print_r($errormsg);die();
}
return $return;
}
}
[ANSWERED]
I have found the solution from that, i have to delete false status in pdo attribute "PDO::ATTR_EMULATE_PREPARES". I think it become error because it will check query in prepare method. And query "use $dbname" is one which has no output and will give error if prepare check is on. Thats all my opinion.

Autoreconnect class for database in php

I am developing a class for Database access and query.
If database is accessible it is working correctly, But problem comes when somehow database is restarted.
Below is the code for library and its users code.
It is able to reconnect with database, but unable to select database. I have tried for 2,5 retry attempts from select_from_db function. But its throwing error Unable to select database test MySQL server has gone away. I am using Windows machine and in sleep time i am executing below command for restarting mysql.
net stop wampmysqld
net start wampmysqld
Please let me know for your suggestion and answers, so that i can improve on it.
<?php
class database {
private $host;
private $user;
private $pswd;
private $name;
private $db_handle;
private $error_msg;
function __construct($db_host, $db_user, $db_pswd, $db_name=NULL){
$this->host = $db_host;
$this->user = $db_user;
$this->pswd = $db_pswd;
$this->name = $db_name;
$this->db_handle = NULL;
$this->error_msg = NULL;
}
function connect(){
if(!is_null($this->db_handle)){
return True;
}
echo "Trying connection..\n";
$this->db_handle = mysql_connect($this->host, $this->user, $this->pswd);
if(!$this->db_handle){
$this->db_handle = NULL;
$this->error_msg = "Unable to connect to database : ".mysql_error();
return False;
}
else{
echo "\nconnected to database successfully!\n";
}
echo $this->name. "\n";
if(!is_null($this->name)){
$result = mysql_select_db($this->name, $this->db_handle);
if(!$result){
$this->db_handle = NULL;
$this->error_msg = 'Unable to select database '.$this->name.' '.mysql_error();
return False;
}
else{
echo "\nselected database successfully!\n";
}
}
return True;
}
function select_from_db($query, $retry=True){
if(!$this->is_connected()){
$result = $this->connect();
echo " 45 : $result\n";
if(!$result)
return $result;
}
echo " executing query \n";
$result = mysql_query($query, $this->db_handle);
if(!$result){
if(stristr(mysql_error(), 'MySQL server has gone away') === False){
$this->error_msg = "Unable to execute query ".mysql_error();
}
else{
if($retry){
$this->db_handle = NULL;
$result = $this->connect_wait(30,5);
return $this->select_from_db($query, False);
}
}
}
echo mysql_error();
echo " returning result $result query \n";
return $result;
}
function insert_to_db($query){
$result = $this->select_from_db($query);
if(!$result)
return $result;
if(stripos($query, 'insert into') !== False){
return mysql_insert_id($this->db_handle);
}
return $result;
}
function is_connected(){
if(is_null($this->db_handle))
return False;
return True;
}
function connect_wait($seconds_to_wait=30, $no_iterations=-1){
$result = $this->connect();
for($counter = 0; ($counter < $no_iterations) && !$result; $counter++){
echo "** $counter \n";
echo "\n$result waiting\n";
sleep($seconds_to_wait);
$result = $this->connect();
echo "\n$result\n";
}
return $result;
}
function disconnect() {
if(!is_null($this->db_handle)){
mysql_close($this->db_handle);
$this->db_handle = NULL;
}
}
function get_error() {
return $this->error_msg;
}
function __destruct() {
$this->disconnect();
}
}
// Connection to database machine
$db_host = 'localhost';
$db_user = 'root1';
#$db_pswd = 'rTpswd$567';
$db_pswd = '';
$db_name = 'test';
$db_table = 'user_login_info';
$db_obj = new database($db_host, $db_user, $db_pswd, $db_name);
if($db_obj->connect()){
echo "Connected";
sleep(20);
echo "Querying";
$query = "select * from $db_table";
$result = $db_obj->select_from_db($query);
if(!$result){
echo mysql_error();
die($db_obj->get_error());
}
while($row = mysql_fetch_assoc($result)){
echo "{$row['user_login_name']} {$row['user_password']}\n";
}
$db_obj->disconnect();
}
?>
PDO is a good library, you don't have to write your own !
You can add a class https://gist.github.com/extraordinaire/4135119 and use it to automatically reconnect when the database is away.

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

PHP using PDO to store session in DB doesnt produce the errors i expected

SOLVED :
answer is in the 2nd post
i try to store session in DB using PDO, but it doesn't produce errors i expected, please read my code.
here's the code for my session handler class:
class MySessionHandler implements SessionHandlerInterface
{
protected $conn = NULL;
public function open($savePath, $sessionName)
{
if(is_null($this->conn))
{
$dsn = 'mysql:host=localhost;dbname=php_advanced';
$username = 'root';
$password = 'password';
try
{
$this->conn = new PDO($dsn, $username, $password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in open function ' . $e->getMessage());
}
}
return TRUE;
}
public function close()
{
echo '<p>close</p>';
$this->conn = NULL;
return TRUE;
}
public function read($id)
{
echo '<p>read</p>';
$query = 'SELECT data FROM session_table WHERE session_id = :id';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
// Kalo query berhasil nemuin id..
if($pdo->rowCount() == 1)
{
list($sessionData) = $pdo->fetch();
return $sessionData;
}
return FALSE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in read function => ' . $e->getMessage());
}
}
public function write($id, $data)
{
echo '<p>write</p>';
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:id, :data)';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->bindValue(':data', $data);
$pdo->execute();
// return the value whether its success or not
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in write function => ' . $e->getMessage());
}
}
public function destroy($id)
{
echo '<p>destroy</p>';
$query = 'DELETE FROM session_table WHERE session_id = :id LIMIT 1';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':id', $id);
$pdo->execute();
$_SESSION = array();
return (bool)$pdo->rowCount();
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in destroy function => ' . $e->getMessage());
}
}
public function gc($maxLifeTime)
{
echo '<p>garbage collection</p>';
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed INTERVAL :time SECOND) < NOW()';
try
{
$pdo = $this->conn->prepare($query);
$pdo->bindValue(':time', $maxLifeTime);
$pdo->execute();
return TRUE;
}
catch(PDOException $e)
{
$this->conn = NULL;
die('error in gc function => ' . $e->getMessage());
}
}
}
$SessionHandler = new MySessionHandler();
session_set_save_handler($SessionHandler);
session_name('my_session');
session_start();
i remove the session_write_close on purpose. This probably sounds stupid, but i want to get the session error to learn more..
here's session script(using the book's code):
require('session_class.php');
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DB Session Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
// Store some dummy data in the session, if no data is present:
if (empty($_SESSION)) {
$_SESSION['blah'] = 'umlaut';
$_SESSION['this'] = 3615684.45;
$_SESSION['that'] = 'blue';
// Print a message indicating what's going on:
echo '<p>Session data stored.</p>';
} else { // Print the already-stored data:
echo '<p>Session Data Exists:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
}
// Log the user out, if applicable:
if (isset($_GET['logout'])) {
session_destroy();
echo '<p>Session destroyed.</p>';
} else { // Otherwise, print the "Log Out" link:
echo 'Log Out';
}
// Reprint the session data:
echo '<p>Session Data:<pre>' . print_r($_SESSION, 1) . '</pre></p>';
// Complete the page:
echo '</body>
</html>';
// Write and close the session:
// session_write_close() <<<<<--- I REMOVE THIS ON PURPOSE TO GET ERROR
?>
but i dont get any error, then i try to use book's mysqli script to connect db and it produces error i expected because i removed the session_write_close()..
can anyone explain why if im using PDO it doesn't generate error? i'm even dont use
register_shutdown_function('session_write_close');
in my session class destructor (on purpose)
NOTE : I'm doing this on purpose because i want to learn more.
the error im expecting is like when im using mysqli connection(connection closed by php at the end of script then session try to write and close but no connection available) :
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 66
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 67
Warning: mysqli_close() expects parameter 1 to be mysqli, null given in /var/www/ullman_advance/ch3/ullman_db.php on line 33
update 1
i recently figured it out that mysqli needs database connection everytime it uses mysqli_real_escape_string() and mysqli_query and because of but what im thinking is my pdo also needs db connection when the script ends -> db connection closed -> MySessionHandler will try to write and close, but there's no db connection since pdo has been closed by php, but no error produced..
update 2
i just tried to pass session_set_save_handler function callback and it produces the errors
<?php
$conn = NULL;
function open_session()
{
echo '<p>open session</p>';
global $conn;
$_dsn = 'mysql:host=localhost;dbname=php_advanced';
$_username = 'root';
$_password = 'password';
$conn = new PDO($_dsn, $_username, $_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return TRUE;
}
function close_session()
{
echo '<p>close session</p>';
global $conn;
$conn = NULL;
return TRUE;
}
function read_session($sid)
{
echo '<p>read session</p>';
global $conn;
$query = 'SELECT data FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
if($pdo->rowCount() == 1)
{
list($session_data) = $pdo->fetch();
echo '<pre>';
print_r($session_data);
echo '</pre>';
return $session_data;
}
else
{
return '';
}
}
function write_session($sid, $data)
{
echo '<p>write session</p>';
global $conn;
$query = 'REPLACE INTO session_table(session_id, data) VALUES(:sid, :data)';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->bindValue(':data', $data, PDO::PARAM_STR);
$pdo->execute();
return $pdo->rowCount();
}
function destroy_session($sid)
{
echo '<p>destroy session </p>';
global $conn;
$query = 'DELETE FROM session_table WHERE session_id = :sid';
$pdo = $conn->prepare($query);
$pdo->bindValue(':sid', $sid, PDO::PARAM_STR);
$pdo->execute();
// clean the session array;
$_SESSION = array();
return (bool)$pdo->rowCount();
}
function clean_session($expire)
{
echo '<p>clean session</p>';
global $conn;
$query = 'DELETE FROM session_table WHERE DATE_ADD(last_accessed, INTERVAL :expire SECOND) < NOW()';
$pdo = $conn->prepare($query);
$pdo->bindValue(':expire', $expire, PDO::PARAM_INT);
$pdo->execute();
return $pdo->rowCount();
}
session_set_save_handler('open_session', 'close_session', 'read_session', 'write_session', 'destroy_session', 'clean_session');
session_name('my_session');
session_start();
but still when im passing MySessionHandler class , it doesn't produce error because of no connection.
SOLUTION
sorry guys my mistake actually its a pretty easy answer why MySessionHandler class doesnt produce error wihtout session_write_close() in the end of script,
session_set_save_handler() by default will register session_write_close() to register_shutdown_function()
so if u want to make your own shutdown function for session then use :
session_set_save_handler($SessionClass, FALSE) , if u do this then u must provide session_write_close() in your class destructor
source : http://php.net/manual/en/function.session-set-save-handler.php
thanks for the tips and your attention

store multiple pdo connections in an array

so i have been trying to debug this issue myself for a few days now and i can't seem to figure out why i'm not getting the results I expect.
My code is rather complex and for a DB connection to be establish it spans across 3 Classes and one config file.
but basically my end usage ends up being
$this->db('test')->query('SELECT * FROM test1');
this establishes a connection to my database by the alias of test the query returns results so i'm good so far.
now my issue is when i try to make a new PDO object.
$this->db('test2')->query('SELECT * FROM test2');
this returns nothing because there is not table called test2 in my test1 object.
but if I do this
$this->db('test2')->query('SELECT * FROM test1');
now this returns the same results from the first PDO object.
I have traced and tracked down every line of code to make sure that the correct parameters are being passed to my database class and that each connection is properly established to the corresponding databases.
now my question is, can you have more than one datbase pdo connection? if so is there a special flag that needs to be set in the PDO options? are my connections being cached somewhere and causing this confusion?
this is my PDO declaration in each new class object stored in my array of connections
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
edit my code that uses the connection
step 1: a call to the parent class
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
return $this->_sys_helper[$hash];
}
return null;
}
step 2: called from the parent class
class DB_System_Helper extends Jinxup
{
private $_con = null;
public function __construct($end = null)
{
$mode = null;
$host = null;
$name = null;
$user = null;
$pass = null;
$port = null;
if (isset($this->config['database']['mode']))
{
$mode = $this->config['database']['mode'] == 'production' ? 'production' : 'development';
if (count($this->config['database'][$mode]) > 1)
{
foreach ($this->config['database'][$mode] as $key => $database)
{
if ($database['#attr']['alias'] == $end)
{
$host = $this->config['database'][$mode][$key]['host'];
$name = $this->config['database'][$mode][$key]['name'];
$user = $this->config['database'][$mode][$key]['user'];
$pass = $this->config['database'][$mode][$key]['pass'];
$port = $this->config['database'][$mode][$key]['port'];
}
}
} else {
$host = $this->config['database'][$mode]['host'];
$name = $this->config['database'][$mode]['name'];
$user = $this->config['database'][$mode]['user'];
$pass = $this->config['database'][$mode]['pass'];
$port = $this->config['database'][$mode]['port'];
}
$this->_con = new PDO_Database_Helper($host, $name, $user, $pass, $port);
} else {
echo 'No database mode specified';
}
}
public function __call($name, $param)
{
return call_user_func_array(array($this->_con, $name), $param);
}
}
step 3: called from DB_System_Helper
class PDO_Database_Helper extends Jinxup
{
private $_con = null;
private $_id = 0;
public function __construct($host, $name, $user, $pass, $port = 3306)
{
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
}
[...]
}
Are you sure that the hashing you're doing is enough to "namespace" each connection in the $this->_sys_helper array?
I suspect the problem lies in the first stage.
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
>>>>>>>>>>>>>> are you sure this is not returning the wrong
>>>>>>>>>>>>>> connection because of how the hashing is working?
return $this->_sys_helper[$hash];
}
return null;
}

Categories