سؤال

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.

هل كانت مفيدة؟

المحلول

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);

?>

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top