gpt4 book ai didi

php - 使用 MySQLi 连接到多个数据库

转载 作者:行者123 更新时间:2023-12-04 22:12:01 26 4
gpt4 key购买 nike

我需要使用 PHP 连接到两个数据库,并使用第一个查询的结果从第二个数据库中获取我需要的其余数据。
因此,对于第二个连接,我需要连接到第二个数据库并选择状态和邮政编码,其中连接 1(客户端)的结果等于数据库 2 中的名字。我该怎么做?

<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {

// get id value
$id = intval($_GET['cd']);
}

$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";

//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value

$mysqli->close();
连接到数据库代码类似于下面
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');

//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}

最佳答案

这没有经过测试,但我认为它会像这样。

<?php

$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');



//build query 1
$query1 = "SELECT * FROM Table";

$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();

//set attributes
$thing1 = $row->Name;
}


//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";

$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();

//set attributes
$thing2 = $row->Name;
}

?>

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

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