使用 php 我需要有 2 个不同的数据库连接

Using php I need to have 2 different connections to the database

我需要将一些行从一个数据库复制到另一个数据库。我遇到了困难。除了 none 之外,我发现了几种似乎有效的方法。我使用的 php 版本是 5.4.

两个连接都在同一台服务器上,但其他一切都不同

这是我找到的 php 代码,它似乎根本不起作用,我无法从第一个数据库select

// Create connection
$wpdb = mysql_connect($servername, $username, $password);

// Check connection
if ($wpdb->connect_error) {
    die("Connection failed: " . $wpdb->connect_error);
} 
echo "Connected local successfully\n";

//$starttime = date("h:i:sa");

$mydb = mysql_connect('localhost','dbname','dbpassword', true);

// Check connection
if ($mydb->connect_error) {
    die("Connection failed: " . $mydb->connect_error);
} 
echo "Connected to Integrity successfully\n";

mysql_select_db($database, $wpdb);
mysql_select_db('wordpress_0', $mydb);

您可以尝试 PDO.that 提供一个通用接口来与许多不同的数据库对话。

$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 
'password');

我拒绝提供对 mysql_ 语法的支持,所以我将提供升级版本。

几乎完全从 php 手册中复制... http://php.net/manual/en/mysqli.select-db.php

代码:

/* attempt and check connection including first database selection "test" */
if (!$mysqli = new mysqli("localhost", "root", "", "test")) {
    // never show the actual error to the public
    echo "<div>Database Connection Error: " , $conn->connect_error , "</div>";
    exit();
}

/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
    // never show the actual error to the public
    echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {    
    echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
    $result->close();
}

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

/* return name of current default database */
if (!$result = $mysqli->query("SELECT DATABASE()")) {
    // never show the actual error to the public
    echo "<div>Syntax Error: " , $conn->error , "</div>";
} else {    
    echo "<div>Default database is: " , $result->fetch_row()[0] , "</div>";
    $result->close();
}
$mysqli->close();

输出:

Default database is: test
Default database is: mysql