PHP和2 mysql中的数据库

时间:2014-08-04 06:57:47

标签: mysqli mysql-workbench

如何连接2个数据库?在第一个我验证用户和用户是否被授权,然后它将访问主数据库。我这样做是为了安全。谢谢你的回答。

3 个答案:

答案 0 :(得分:0)

是的,您可以创建两个与mysql的连接,使用不同的变量进行连接

<?php
$con1 = mysqli_connect("db1server","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$con2 = mysqli_connect("db2server","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

?>

并在所需服务器上运行查询

答案 1 :(得分:0)

您可以访问任意数量的数据库

例如。

$dbcon1= mysqli_connect(host,username,password,dbname1);


$dbcon2=mysqli_connect(host,username,password,dbname2);

使用多个数据库时要注意的重要事项确保关闭(mysqli_close(dbconnection))数据库,
  在访问其他数据库之前作为一种良好做法

答案 2 :(得分:0)

您应该检查功能mysqli::select_db/mysqli_select_db

以下是一个例子:

面向对象的风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

/* change db to world db */
$mysqli->select_db("world");

/* return name of current default database */
if ($result = $mysqli->query("SELECT DATABASE()")) {
    $row = $result->fetch_row();
    printf("Default database is %s.\n", $row[0]);
    $result->close();
}

$mysqli->close();
?>

程序风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

/* change db to world db */
mysqli_select_db($link, "world");

/* return name of current default database */
if ($result = mysqli_query($link, "SELECT DATABASE()")) {
    $row = mysqli_fetch_row($result);
    printf("Default database is %s.\n", $row[0]);
    mysqli_free_result($result);
}

mysqli_close($link);
?>

以上示例将输出:

Default database is test.
Default database is world.