目前我通过这个连接到数据库服务器
@$db_connect = mysql_connect('localhost','user','xxx', true);
由于在同一个查询中查询多个数据库,我必须连接到数据库服务器(不是特定的数据库名称)。
谁能建议我如何用 PDO 做同样的事情?
目前我通过这个连接到数据库服务器
@$db_connect = mysql_connect('localhost','user','xxx', true);
由于在同一个查询中查询多个数据库,我必须连接到数据库服务器(不是特定的数据库名称)。
谁能建议我如何用 PDO 做同样的事情?
$dsn
即使您要跨多个数据库进行查询,您仍然需要在 PDO 中选择一个数据库。这不是真正的问题,因为在您的查询中您将使用模式dbname.tablename.columnname
。仅查询 中实际指定的数据库时$dsn
,不需要使用dbname
.
当然,您将需要在您打算为连接中指定的用户使用的所有数据库上授予权限。
// Need more than just testdb, but specify it here anyway
// It doesn't matter which one you choose here- pick the one you'll use the most I suppose
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Query across 2 databases, and specify aliases for the dbname.tablename
$stmt = $dbh->prepare("
SELECT
tdb.col1,
other.col2
FROM
testdb.table1.col1 AS tdb
JOIN otherdb.table2.col2 AS other
ON tdb.col1 = other.col2
");
你可以在 PDO 中做同样的事情。MySQL DSN 字符串的dbname
属性是可选的。
$db = new PDO('mysql:host=localhost', $user, $pass);
但是,在这种情况下,您需要执行use databasename
或确保所有查询都使用格式SELECT * FROM databasename.tablename
。