Mysqli - When opening 2 connections to the same host with mysql, but different databases, does mysqli open the connection once?

前端 未结 2 2010
长情又很酷
长情又很酷 2021-01-06 05:34

When I have a situation like this:

$databaseA = new mysqli($host,$user,$pass,\"databaseA\");
$databaseB = new mysqli($host,$user,$pass,\"databaseB\");


        
相关标签:
2条回答
  • 2021-01-06 05:52

    For every mysqli-object there will be a separate connection.

    Try a

    SHOW FULL PROCESSLIST; 
    

    on your MySQL server during runtime, you'll see two different processes connected from the same host if your example is implemented.

    0 讨论(0)
  • 2021-01-06 05:54

    Assuming you have a good reason to use two different databases, the only way to make this work with a single connection is with a user that has privileges to access both databases. It would go something like this:

    $db = new mysqli($host,$user,$pass); // connect to the MySQL server without specifying a database
    
    mysqli_select_db('databaseA', $db); // Specify your default/most-used database
    

    If you don't explicitly specify databaseB in your query, MySQL will use the default (databaseA). So a query that gets one column from databaseB and two from databaseA would look like this:

    $query = "SELECT databaseB.table.column, table.column, table.column2";
    
    0 讨论(0)
提交回复
热议问题