This discussion is archived
0 Replies Latest reply: Oct 17, 2013 10:20 AM by 7b8fd95e-5e5d-48d9-89f9-7f47feb49b53 RSS

MySQL Database Connection (two databases at the same time)

7b8fd95e-5e5d-48d9-89f9-7f47feb49b53 Newbie
Currently Being Moderated

I have never had to open more than one MySQL database from within the same website before, but I do now.  The website I have is designed where all the content comes from within the main database.  I am building an Inventory system that I want within it's own database, in the event I would ever need to move the application to another server or something, I don't want this data residing in the main database.

 

Currently, I open the database connection from within a file called "common.php" that resides in a directory called "lib" that can be accessed from the root directory.  Below is the proposed code that would be placed within the "common.php" file:

 

// Define Database Variables

$dbserver = "127.0.0.1";

$dbuser  = array('clevelan_user1', 'clevelan_user2');

$dbpass  = array('P@ssw0rd', 'P@ssw0rd2');

$dbname  = array('clevelan_database1', 'clevelan_database2');

 

// Start Session

session_start();

 

// Connect to Databases

connectdb($dbserver, $dbuser[0], $dbpass[0], $dbname[0]);

connectdb2($dbserver, $dbuser[1], $dbpass[1], $dbname[1]);

 

// Database 1 Connection

function connectdb($dbserver, $dbuser, $dbpass, $dbname) {

// connects to db


  global $connection;

  $connection = @mysql_connect($dbserver, $dbuser, $dbpass) or die ("could not connect to server");

  $db = @mysql_select_db($dbname, $connection) or die ("could not select databsase");

  return $connection;

}

 

// Database 2 Connection

function connectdb2($dbserver, $dbuser, $dbpass, $dbname) {

// connects to db


  global $connection2;

  $connection2 = @mysql_connect($dbserver, $dbuser, $dbpass) or die ("could not connect to server");

  $db2 = @mysql_select_db($dbname, $connection2) or die ("could not select databsase");

  return $connection2;

}

 

//End of Code Within the "common.php"

 

From within any page of the website, I want to access both connections by placing an include at the top of each page:

 

include_once("lib/common.php");

 

Currently, when I run the code above, any page within the website (the home page) provides error messages with regards to database connectivity (the pages are looking for there content from within the second database.  It's as if the second database is the only database seen by the website.

 

I need help figuring out how I can have two MySQL databases open at the same time (the second database will only be open for short periods of time and then closed).  But the main database is always open.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points