Connect to Multiple Databases using MySQLi

后端 未结 3 1703
花落未央
花落未央 2021-01-20 21:44

I 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 c

3条回答
  •  天命终不由人
    2021-01-20 22:08

    If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:

    // Don't forget to enable error reporting!
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    
    $db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
    $db1->set_charset('utf8mb4'); // always set the charset
    
    $db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
    $db2->set_charset('utf8mb4'); // always set the charset
    

    Then you can perform your two statements in each database separately.

    // get id value
    $id = intval($_GET['cd']);
    
    // Get client name from DB1
    $stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
    $stmt->bind_param('s', $id);
    $stmt->execute();
    $client = $stmt->get_result()->fetch_object();
    
    // Get state and zipcode from DB2
    $stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName  = ?');
    $stmt->bind_param('s', $client->client);
    $stmt->execute();
    $location = $stmt->get_result()->fetch_object();
    
    echo $location->state;
    echo $location->zipcode;
    

提交回复
热议问题