gpt4 book ai didi

php - 是否可以连接到两个不同的mysql数据库?

转载 作者:太空宇宙 更新时间:2023-11-03 12:07:39 24 4
gpt4 key购买 nike

我有 2 个数据库需要连接,但我不知道如何将查询放入我的代码中。

我有 2 页代码。 1用于表格,另一个用于在我们填写表格后显示数据。我是否需要在两个页面上都放置一个新查询,或者两者都不需要?

当我尝试在两个页面上建立第二个连接时,整个页面都无法正常工作。

我为两个页面建立的连接看起来像这样:

<?php 
session_start();
include('conn.php');
include('connection2.php');

?>

对于第二个数据库:

<?php
define('DB_HOST2','localhost');
define('DB_USER2','root');
define('DB_PASSWORD2','');
define('DB_NAME2','smile2');

$dbc = @mysql_connect(DB_HOST2,DB_USER2,DB_PASSWORD2) OR Die ('Could not connect to MySQL: '. mysql_error());
@mysql_select_db (DB_NAME2) OR Die ('Could not select database: '. mysql_error());
?>

对于第一个数据库:

<?php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASSWORD','');
define('DB_NAME','smile');

$dbc = @mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) OR Die ('Could not connect to MySQL: '. mysql_error());
@mysql_select_db (DB_NAME) OR Die ('Could not select database: '. mysql_error());
?>

如何让 @mysql_* 变为:

<?php
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");

//you might wanna switch back to the first database
mysql_select_db("database_1");
?>

最佳答案

您可以使用 PHP 函数 mysql_select_db 在数据库之间切换。像这样:

<?php
//The preferred way:
//connect
mysqli_connect("localhost", "user", "password");
//select first database
mysqli_select_db("database_1");
//do query
mysqli_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysqli_select_db("database_2");
//do query on other database
mysqli_query("SELECT * FROM `other_table` WHERE `field` = 2");

//you might wanna switch back to the first database
mysqli_select_db("database_1");



//The old way
//connect
mysql_connect("localhost", "user", "password");
//select first database
mysql_select_db("database_1");
//do query
mysql_query("SELECT * FROM `table` WHERE `field` = 1");
//select second database
mysql_select_db("database_2");
//do query on other database
mysql_query("SELECT * FROM `other_table` WHERE `field` = 2");

//you might wanna switch back to the first database
mysql_select_db("database_1");
?>

关于php - 是否可以连接到两个不同的mysql数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25746973/

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