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

标签 php mysqli

我需要使用 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/

相关文章:

php - 当有两个匹配数据时,只获取一个 Json 对象响应?

php - 输入错误的用户名和密码时登录成功

php - 如何检查 mysqli_query 是否删除了任何行

javascript - 单击div时如何将坐标保存在db中并带有注释并根据div中的坐标显示?

php mysqli 获取显示数组结果的数据但无法回显(显示 NULL)

php - Laravel 在命名空间中找不到类

php - 使用 PHP/CodeIgniter 在 MySQL 中获取最后执行的查询

javascript - 在页面加载时加载模式并在 5 秒后重定向

php - $stmt->执行() : How to know if db insert was successful?

php - 在 php 中正确处理来自 mysqli 准备语句的数据