gpt4 book ai didi

php - 使用php用户定义函数连接多个数据库

转载 作者:行者123 更新时间:2023-11-29 13:37:11 25 4
gpt4 key购买 nike

这是 config.php 的代码,我将此文件包含在所有 php 文件中:

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
mysql_select_db('test1', $conn) or die('Could not select database.');
return $conn;
}
db_connect1();
?>

这里我需要连接另一个数据库test2。

最佳答案

您可以多次调用 mysql_connect(),但如果参数相同,则需要为另一个连接传递 true

<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn1 = mysql_connect($db_name, $db_user, $db_pass);
$conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
mysql_select_db('test1', $conn1) or die('Could not select database test1.');
mysql_select_db('test2', $conn2) or die('Could not select database test2.');

$conn = new stdClass();
$conn->conn1 = $conn1;
$conn->conn2 = $conn2;

return $conn;
}
$conn = db_connect1();

然后要查询数据库 test1,请执行以下操作:

mysql_query('select * from tablename', $conn->conn1);

对于数据库 test2:

mysql_query('select * from tablename', $conn->conn2);

?>

关于php - 使用php用户定义函数连接多个数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18584374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com