Pwned Pwned - 1 year ago 78
MySQL Question

PHP - Multiple MySQL Connections

Ok so this is my code for the connection:

$servername = "host";
$username = "user";
$password = "pass";
$db1 = "db1";
$db2 = "db2";
// Create connection
$conn = new mysqli($servername, $username, $password, $db1); // $db1 is here as the default, is this ok?
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

Then I run a function with this connection and it works for the

$sql = "SELECT etc etc;
$result = $conn->query($sql);

etc etc

The problem is when I try to change the db to
, I use this:


And now it only returns the value of the 2nd Database
, and the one from
doesn't show up on the page anymore, it doesn't show any value.

Thanks for Reading.

Answer Source

You have use two different connections while connecting different databases

Database One Connection:

$conn = new mysqli($servername, $username, $password, $db1);
$sql = "SELECT etc etc;
$result = $conn->query($sql);

Database Two Connection:

$conn1 = new mysqli($servername, $username, $password, $db2);
$sql = "SELECT etc etc;
$result = $conn1->query($sql);

The Problem is that you have already assigned the conn to DB1 and hence if you run by selecting the DB2 it will be displaying error or no results will be produced. Hence while selecting multi databases you can use different connection variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download