Connect to Multiple Databases using MySQLi in pHP

2020-04-11 09:58发布

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.

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

标签: php mysqli
2条回答
狗以群分
2楼-- · 2020-04-11 10:21

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

?>
查看更多
冷血范
3楼-- · 2020-04-11 10:21

You would need to make 2 different connections

<?php
    $mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');

    $mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');

Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database

So

$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
         ->fetch_object();

$locn = $mysqliDB2->query("SELECT state,zipcode 
                           FROM location 
                           WHERE ClientID = {$client->FirstName}")
                  ->fetch_object();
echo $locn->state;
echo $locn->zipcode;

I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.

查看更多
登录 后发表回答