在pHP中使用MySQLi连接到多个数据库 [英] Connect to Multiple Databases using MySQLi in pHP

查看:37
本文介绍了在pHP中使用MySQLi连接到多个数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前需要使用PHP连接到两个数据库,并使用第一个查询的结果从第二个数据库中获取我需要的其余数据.

I currently need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.

因此对于第二个连接,我需要连接到第二个数据库,并选择状态和邮政编码,其中连接1(客户端)的结果与数据库2中的名字相等.

So for the second connection I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?

<?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();
?>

与数据库代码的连接与以下类似

Connection To Database Code is similar to the below

<?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);
}
?>

推荐答案

这未经测试,但我认为它会像这样.

This isn't tested, but I think it would go something like this.

<?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连接到多个数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆