• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 404
  • Last Modified:

Sharing data between databases using PHP

I just found the answer to a question describing how you can reference data across 2 databases, it was very helpful.

My question is how can you access data from 2 different databases within 1 php page?

For example I have a php script, db_functions.php, that connects to the database Test1, I run it at the beginning of each of my pages that need to access the database, it has simple php functions that connect to the mysql database Test1. So lets say I am on page1.php and I am connecting to Test1.table1, but I have another table in another database that I need to access at the same time, lets say Test2.table2. How do I go about connecting to the second table in the second database? Is this possible? The idea would be to have redundant information in one database, and instead of recreating a table, for example users, within 4 or 5 different databases, you would keep users seperate and just access it when it is required, like for a login...

I will show my code for db_functions.php and how I connect in my page1.php.
//db_functions.php
<?php

$db = mysql_connect("1.2.3.4:/mysql","username","password");

function openDB()
{
	global $db;
	if(!$db)
	{
		die("db failed: " . mysql_error());
	}
	
	$db_selected = mysql_select_db('Test1', $db);
	if (!$db_selected) {
		die ("Can\'t use db : " . mysql_error());
	}
}
	
function closeDB()
{
	global $db;
	mysql_close($db);
}

function runQuery($query)
{
	$result = mysql_query("$query");
	if (!$result) {
		return mysql_errno();
	}
	return $result;
}
?>

//page1.php
<?php
include 'db_functions.php';

opendb();
....
$query1 = "select firstname, lastname from table1'";
$result = runQuery($query1);
....
closedb();
?>

Open in new window

0
bmwlaval
Asked:
bmwlaval
1 Solution
 
johanntagleCommented:
As long as you have access to both DB's even if you're currently at Database1 you should be able to access tables in Database2 via Database2.TableA notation
0
 
xtermCommented:
Just open multiple DB handles:

$db1=mysql_connect("1.2.3.4:/mysql","username","password");
$db2=mysql_connect("4.3.2.1:/mysql","username","password");

$db_selected1 = mysql_select_db('Test1', $db1);
$db_selected2 = mysql_select_db('Test1', $db2);

You can open as many as you like - just try to remember to mysql_close() all of them when you're done :)
0
 
bmwlavalAuthor Commented:
thanks
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now