This is an Error Message
This is a Success Message
This is an Informative Message

Topics: 15   |   Posts: 14   |   Comments: 12   |   Members: 227

  • 43
  • 1

Instantly Switching MySQL Database with PHP

omari Mon May 07, 2012 - 11:10 am

Omari Celestine

If you are working with PHP and have configuration file similar to below while trying to switch between MySQL databases for minimal information gathering then here is a basic solution.

Database connection file:


<?php
$dbhost="localhost";
$dbname="mydb";
$dbuser="username";
$dbpasswd="password11";
// connect to the db
$link = mysql_connect($dbhost, $dbuser, $dbpasswd);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
    die ('Can\'t use dbreviews : ' . mysql_error());
}
?>



Now let's say you are outputting information using that configuration and want to get that bit from another database called "mydb2".


$data = mysql_query("SELECT * FROM table WHERE ID = '5'") or die(mysql_error());
$info = mysql_fetch_array($data);

$title = $info['title'];

// Switch to other database
$dbname2 = "mydb2";
mysql_select_db($dbname2, $link);

// Get information from table in second database
$data2 = mysql_query("SELECT * FROM table WHERE ID = '5'") or die(mysql_error());
$info2 = mysql_fetch_array($data2);

$description = $info2['description'];

// Switch back to original database
$dbname = "mydb";
mysql_select_db($dbname, $link);



This would allow you to instantly move from the original database, to another database and back without any affiliated issues.

0 ATTACHMENTS

Login or Register to leave a comment.

Topic Search
Get Started