1

I've been using PHP mysqli functions since long but never came accross such a senario where I need to join two tables from different database.

Suppose I've table t1 from database d1 & table t2 from database d2 with a common column say id.

I am stuck here:

mysqli_select_db($conn1,"d1") or die("Error selecting database");

$conn2 = mysqli_connect("localhost","root","") or die("Error connecting Database");
mysqli_select_db($conn2,"d2") or die("Error selecting database");

$sql = "SELECT * from d1.t1 tab1 inner join d2.t2 tab2 on tab1.id = tab2.id";
$result = mysqli_query(**don't know**,$sql);
$row = mysqli_fetch_array($result);

Please tell me what should I write in place of "don't know". Also suggest any better way, if any to get this done.

Thanks in advance.:)

Karan Pal
  • 41
  • 3
  • Are `d1` and `d2` different databases on **the same** server, or different databases on **different** servers? – Matteo Tassinari May 07 '20 at 10:28
  • have you tried just supplying `$conn1`? Was there a problem? As long as the user has permission to select from both databases/tables, then it should be fine. You have an open connection to the server. The only issue would be if the databases are actually on different servers. – ADyson May 07 '20 at 10:28
  • It is a very bad idea to use `die` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman May 07 '20 at 11:29
  • They both are in same server. – Karan Pal May 07 '20 at 11:45
  • Thanks. It worked with both $conn1 and $conn2. I just thought that mysqli_select_db() gives access only to the database passed to it. – Karan Pal May 08 '20 at 05:06
  • @KaranPal No it just selects at as the default database, so that you don't have to prefix all the table names etc in your queries with the name of the database – ADyson May 08 '20 at 08:40

0 Answers0