0

This is the code for config.php I am including this file in all php files:

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
    global $db_name, $db_user, $db_pass;
    $conn = mysql_connect($db_name, $db_user, $db_pass);
    mysql_select_db('test1', $conn) or die('Could not select database.');
    return $conn;
}
db_connect1();
?>

Here i need to connect with another one database test2.

2 Answers 2

1

You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for another connection

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
    global $db_name, $db_user, $db_pass;
    $conn1 = mysql_connect($db_name, $db_user, $db_pass);
    $conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
    mysql_select_db('test1', $conn1) or die('Could not select database test1.');
    mysql_select_db('test2', $conn2) or die('Could not select database test2.');

    $conn = new stdClass();
    $conn->conn1 = $conn1;
    $conn->conn2 = $conn2;

    return $conn;
}
$conn = db_connect1();

Then to query database test1, do this:

mysql_query('select * from tablename', $conn->conn1);

and for database test2:

mysql_query('select * from tablename', $conn->conn2);

?>

Sign up to request clarification or add additional context in comments.

Comments

0

try this

$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1($dbname) {
   global $db_name, $db_user, $db_pass;
   $conn = mysql_connect($db_name, $db_user, $db_pass);
   if($conn) {
      mysql_select_db($dbname, $conn) or die('Could not select database.');
      return $conn;
   } else {
      die("Error occurred while connect to the server.");
   }
}

Every time you call the function and set argument.

echo db_connect1('test1');
echo db_connect1('test2');

Echo the function because you are using return keyword and checked that if it returns 1 its means your server connection is ok.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.