How do you connect to multiple MySQL databases on a single webpage?

后端 未结 11 2376
青春惊慌失措
青春惊慌失措 2020-11-22 05:06

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases

11条回答
  •  借酒劲吻你
    2020-11-22 05:39

    If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.

    You would connect through PDO, like this:

    try {
      $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
    } catch (PDOException $ex) {
      echo 'Connection failed: ' . $ex->getMessage();
    }
    

    (Of course replace databasename, username and password above)

    You can then query the database like this:

    $result = $db->query("select * from tablename");
    foreach ($result as $row) {
      echo $row['foo'] . "\n";
    }
    

    Or, if you have variables:

    $stmt = $db->prepare("select * from tablename where id = :id");
    $stmt->execute(array(':id' => 42));
    $row = $stmt->fetch();
    

    If you need multiple connections open at once, you can simply create multiple instances of PDO:

    try {
      $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
      $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
    } catch (PDOException $ex) {
      echo 'Connection failed: ' . $ex->getMessage();
    }
    

提交回复
热议问题