Jump to content

connection to two databases using a database class


wrathican

Recommended Posts

hey people, im trying to connect to two databases in a project and it only seems to be connected to one.

 

im using a database class to connect/query the database and here it is:

<?php

class Database {
var $conn; # the connection
var $seed; # seed for password table

# Containing datbase conenction info
static private $defaultConfig = array();
private $config = array();

# Used to change the config statically, before instanciation
static public function setDefaultConfig(array $config){
	self::$defaultConfig = $config;
}

function Database() {
	# Added - sets $config using defaultConfig that should have been set before instanciation
	$this->config = self::$defaultConfig;
	$this->seed = '02dbdcb55dd615d28c44f2c2ae3c2c96386a5586';

	$this->conn = mysql_connect($this->config['host'], $this->config['name'], $this->config['pass'], true);
	mysql_select_db($this->config['daba']);

	}
}


# Used to change the config after instanciation
public function setConfig(array $config){
	foreach ($config as $key => $value) {
		$this->config[$key] = $value;
	}
	#return $this;
	mysql_close($this->conn);
	$this->conn = mysql_connect($this->config['host'], $this->config['name'], $this->config['pass']);
	mysql_select_db($this->config['daba']);
} // function


# simple select, insert and update functions
# IMPORTANT: all need values to be sanitised before passing user-input to them.

function db_select($which_cols, $which_table, $where_condition = 1, $other = '') {
	# input values:
	# $which_cols: '*' (all columns), 'col_a' for a single column, 'col_a, col_b, col_c' for multiple columns
	# $which_table is fairly obvious
	# $where_condition: 1 or '1' or left blank to return all values from the table, otherwise example string ('col_a = val_a AND col_b = val_b')
	# $other: defaults to empty string. Any other query conditions, like ORDER BY clause, LIMIT clause, etc.
	# It actually tends to be easier (although not quicker) to retrieve extra records and use php to filter those wanted. Especially for ordering.

	$query = sprintf(
		'SELECT %s FROM `%s` WHERE %s %s',
		$which_cols,
		$this->config['pref'] . $which_table,
		$where_condition,
		$other
	);
	$result = mysql_query($query);
	# echo $query;
	$output = array();
	if (!$result) return($output);
	while ($row = mysql_fetch_assoc($result)) {
		foreach ($row as $k => $v) {
			$row[$k] = stripslashes($v);
		}
		$output[] = $row;
	}
	return($output);
	#returns 2-dimensional array, each element of outer array is an associative array based on one row of the table.
}

function db_insert($which_table, $an_array) {
	# input values:
	# $which_table is fairly obvious
	# $an_array: an associative array: the keys are the column names, the values are the values to be inserted.
	$query = sprintf(
		'INSERT INTO `%s` (`%s`) VALUES (\'%s\')',
		$this->config['pref'] . $which_table,
		implode('`, `', array_keys($an_array)),
		implode("', '", $an_array)
	); # !
	# echo $query;
	$result = mysql_query($query);
}

function db_update($which_table, $an_array, $where_condition = 1, $other = '') {
	# input values: similar to above two functions
	$temp = array();
	foreach($an_array as $k => $v) {
		$temp[] = "`$k` = '$v'";
	}
	$query = sprintf(
		'UPDATE `%s` SET %s WHERE %s',
		 $this->config['pref'] . $which_table,
		 implode (', ', $temp),
		 $where_condition
	);
	# echo $query;
	$result = mysql_query($query);
}

function db_delete($which_table, $where_condition) {
	# similar input values again
	$query = sprintf(
		'DELETE FROM `%s` WHERE %s',
		$this->config['pref'] . $which_table,
		$where_condition
	);
	# echo $query;
	$result = mysql_query($query);
}
}
?>

 

this is how i instanciate it:

<?php

Database::setDefaultConfig(array('pref' => '', 
							'host' => 'localhost', 
							'name' => 'root', 
							'pass' => '', 
							'daba' => 'pelleting'
						));
# Pelleting
$db = new Database();
# Newburgh - with default conn info
$nb = new Database();
# change Newburgh conn info
$nbConf = array('pref' => '', 
			'host' => 'localhost', 
			'name' => 'root', 
			'pass' => '', 
			'daba' => 'newburgh'
		);
$nb->setConfig($nbConf);

?>

 

any of the queries i make using $db do not return any results, but $nb does.

I gather its because im overwriting the database connection stuff, but im using a different object to each database.

 

so i'm a little confused.

 

Should this work? if not why not? if so, why isnt it?

 

Thanks in advanced

 

Wrath

The MySQL extension handles MySQL connections oddly.  It assumes a connection is the same if the host/port/auth match.

 

 

 

For example:

 

C:\Users\Corbin>php -r "var_dump(mysql_connect('localhost', 'root', 'root')); var_dump(mysql_connect('localhost', 'root', 'root'));"

resource(4) of type (mysql link)

resource(4) of type (mysql link)

 

 

So, a simple fix, is to use 127.0.0.1 and localhost.

 

Example:

 

C:\Users\Corbin>php -r "var_dump(mysql_connect('localhost', 'root', 'root')); var_dump(mysql_connect('127.0.0.1', 'root', 'root'));"

resource(4) of type (mysql link)

resource(5) of type (mysql link)

 

 

 

Then you can select two different DBs.

 

 

What's happening now is that you're passing the same resource to the mysql_select_db function twice.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.