Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysqli

When I have a situation like this:

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

When I define $databaseB, does mysqli try to re-open the connection to $host, or does it use the cached connection from $databaseA?

Thanks

like image 532
P. Danielski Avatar asked Dec 04 '22 04:12

P. Danielski


1 Answers

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";
like image 58
snout1979 Avatar answered May 14 '23 20:05

snout1979