How to execute dependent multiple SQL queries from multiple databases via same PHP web page? We can connect a single PHP page with more than one databases. But what about executing multiple dependent queries that belong to different databases?

mysqli_multi_query(connection,query);


does not seems helpful as it asks for a single shot while my second query uses result of the first. I tried using two connection strings and using them with two queries but this does not seems to be helpful. My code uptil now is here:

&lt;div class="image fit"&gt;
   &lt;?php
   //Connection with DB
   $user = "root";
   $pass = "";
   $db1 = "raw_images";
   $db2 = "labelled_images";
     $conn1 = mysqli_connect('localhost',$user,$pass,$db1,true);
   $conn2 = mysqli_connect('localhost',$user,$pass,$db2,true);
   if(!$conn1||!$conn2)
   {
   die(mysqli_error());
   }
*/
//query to display image
   $query1 = "SELECT * FROM raw_images.tbl_raw_image WHERE id IN
    (SELECT id FROM (SELECT id FROM raw_images.tbl_raw_image ORDER BY RAND() LIMIT 1) t)";
   $sth = $conn1-&gt;query($query1);
   $result=mysqli_fetch_array($sth);
   $id=$result['id'];
   $image=$result['image'];
   $query2="INSERT INTO `labelled_image`.`tbl_labelled_image` (`id`,`image`, `label`, `id_in_raw_image_table`) VALUES (NULL, '$image', '0', '$id')";
   $rs  = mysqli_query($conn2, $query2);
   echo '&lt;img src="data:image/jpeg;base64,'.base64_encode( $image ).'"/&gt;'; ?&gt;
       &lt;/div&gt;


When using such approach, first query executes successfully but not the second one. While executing it simply does not inserts values which I retrieved from the first table but only the values which are given directly to the query like label which I pass zero hence it results in the following outcome:
You shouldn't need two connections for this as the databases in your code are on the same MySQL instance and the DB user apparently has grants to use both.

All you have to do is prefix your table with the database name in the SQL statements, as you have already done. You can use the same connection for both. (It doesn't matter which database is specified in the connection parameters, I suspect this parameter can even be empty.)