How to connect two different Database in a PHP Class – Simple Script

Sometimes you may need to connect two different databases for a project and you may feel difficult to do that right?.

Don’t worry it’s really simple if you are using a PHP Class in your project.


private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}

How to connect to the different databases if you use the above method?


<?php

class Data {

private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}

function get_first_db_details(){
//this is how you can connect to the database
self::_connectDB1();

$sql = "SELECT * from firstdbtable";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)){
$allrecords[] = $row;
}
return $allrecords;
}

function get_second_db_details(){
//this is how you can connect to the 2nd database
self::_connectDB2();

$sql = "SELECT * from seconddbtable";
$query = mysql_query($sql);
while($row = mysql_fetch_assoc($query)){
$allrecords[] = $row;
}
return $allrecords;
}

}
?>

I hope you would have understood reading the comments (green color) in the above script!!

Leave a Reply

Theme: Overlay by Kaira
Agurchand