是否可以连接到两个不同的mysql数据库?

时间:2014-09-09 14:17:55

标签: php mysql

我有2个需要连接的数据库,但我不知道如何将查询放入我的代码中。

我有2页代码。 1表示表单,另一表单填写表单后显示数据。我是否需要在两个页面上都放置新查询?是不是?

当我尝试在两个页面上放置第二个连接时,整个页面都不起作用。

我所建立的连接对于两个页面都是这样的:

<?php 
 session_start();
 include('conn.php');
 include('connection2.php');

?>

对于第二个数据库:

<?php
  define('DB_HOST2','localhost');
  define('DB_USER2','root');
  define('DB_PASSWORD2','');
  define('DB_NAME2','smile2');

  $dbc = @mysql_connect(DB_HOST2,DB_USER2,DB_PASSWORD2) OR Die ('Could not connect to MySQL: '. mysql_error());
  @mysql_select_db (DB_NAME2) OR Die ('Could not select database: '. mysql_error());
?>

对于第一个数据库:

<?php
  define('DB_HOST','localhost');
  define('DB_USER','root');
  define('DB_PASSWORD','');
  define('DB_NAME','smile');

  $dbc = @mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) OR Die ('Could not connect to MySQL: '. mysql_error());
  @mysql_select_db (DB_NAME) OR Die ('Could not select database: '. mysql_error());
?>

如何将@mysql_*更改为:

<?php
  //connect
  mysql_connect("localhost", "user", "password");
  //select first database
  mysql_select_db("database_1");
  //do query
  mysql_query("SELECT * FROM `table` WHERE `field` = 1");
  //select second database
  mysql_select_db("database_2");
  //do query on other database
  mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");

  //you might wanna switch back to the first database
  mysql_select_db("database_1");
?>

3 个答案:

答案 0 :(得分:3)

您可以使用PHP函数mysql_select_db在数据库之间切换。像这样:

<?php
//The preferred way:
//connect
mysqli_connect("localhost", "user", "password");
//select first database
mysqli_select_db("database_1");
//do query
mysqli_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysqli_select_db("database_2");
//do query on other database
mysqli_query("SELECT * FROM `other_table` WHERE `field` = 2");

//you might wanna switch back to the first database
mysqli_select_db("database_1");



//The old way
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");

//you might wanna switch back to the first database
mysql_select_db("database_1");
?>

答案 1 :(得分:0)

一次只做一步,就像这里一样:

<?php
  $link = mysql_connect("localhost", "mysql_user","mysql_password")
  or die("Could not connect to MYSQL"); 

  $selected_db = mysql_select_db('Database_Name', $link) 
  or die ('Sorry, could not connect to Database');


  echo 'Connected successfully';


  mysql_close($link);

?>

然后第二个:

<?php
  $link = mysql_connect("localhost", "mysql_user","mysql_password")
  or die("Could not connect to MYSQL"); 

  $selected_db = mysql_select_db('Database_Name', $link) 
  or die ('Sorry, could not connect to Database');


  echo 'Connected successfully';


  mysql_close($link);

?>

答案 2 :(得分:0)

    <?php
    class manageDB{

    private $dbStatus = false;
    private $mode = 'debug';

    private $curCon = 'db1';
    private $db = '';
    private $con = '';

    private $details = array(
        'db1'=>array(
            'server'=> '',
            'user'  => '',
            'pass'  => '',
            'db'    => ''                   
        ),
        'db2'=>array(
            'server'=> '',
            'user'  => '',
            'pass'  => '',
            'db'    => ''               
        )
    );

    //Init object
    function __construct() {

        $this->curCon = ($GLOBALS['isDebug']) ? 'db1' : 'db2';

    }    

    public function defineDB($options, $type){

        if(empty($type)){

            $this->curCon = 'db1';
            $this->details[$this->curCon]['server'] = $options['server'];
            $this->details[$this->curCon]['user'] = $options['user'];
            $this->details[$this->curCon]['pass'] = $options['pass']; 
            $this->details[$this->curCon]['db'] = $options['db'];
            $this->con = null; 

        } else {

            $this->curCon = $type;

        }

        $this->returnDB = FALSE;

        if($this->dbStatus == TRUE) $this->open();
    }

    public function open(){
        $this->con = mysql_connect($this->details[$this->curCon]['server'], $this->details[$this->curCon]['user'], $this->details[$this->curCon]['pass']);
        if (!$this->con) { die('Could not connect: ' . mysql_error()); };
        mysql_select_db($this->details[$this->curCon]['db'], $this->con);
        $this->dbStatus = true;
    } 

    public function close(){
        mysql_close($this->con);    
        unset($this->connectStatus);
        $this->dbStatus = false;
    } 

    public function changeDB($db){

        if($this->details[$this->curCon]['db'] != $db) mysql_select_db($db, $this->con);
        $this->returnDB = TRUE;
        return $this;

    }

    public function qry($query) {

      $args  = func_get_args();
      if(count($args) > 1){
          $query = array_shift($args);
          $query = str_replace("?", "%s", $query);
          $args  = array_map('mysql_real_escape_string', $args);
          array_unshift($args,$query);
          $query = call_user_func_array('sprintf',$args);           
      }

      $result = mysql_query($query);

      //Check if we need to return to default table
      if(isset($this->returnDB)){

        mysql_select_db($this->details[$this->curCon]['db'], $this->con);
        $this->returnDB = FALSE; 

      }

      if($result){
         return $result;
      }else{
         $error = "Error";
         return $result; 
      }

    }

    public function checkStatus(){ echo $this->dbStatus; }
}; 

$db = new manageDB();   
?>  

用法:
对于正常操作使用

$select = $db->query(...);

切换数据库使用

$select = $db->changeDB('db_name')->query(...);