Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Multiple MySQL Connections [duplicate]

Tags:

php

mysql

mysqli

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 $db1:

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

etc etc

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

$conn->select_db($db2);

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

Thanks for Reading.

like image 535
Pitipaty Avatar asked Jul 05 '26 03:07

Pitipaty


1 Answers

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.

like image 143
Naresh Kumar P Avatar answered Jul 06 '26 19:07

Naresh Kumar P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!