简体   繁体   中英

How can connect to two databases in same time and query data in mysql, I have same host

I have two Database, A & B how I can copy data from A to B using MySQL, i did like there something wrong, there are two same tables called members in A & B, and i want copy username from A.members to B.members. there is error ! can I do that using Mysql, anyone can help me to solve this problem because I must connect to databases A & B in same time then query data

    mysql_connect("$host", "$user", "$pass"); mysql_select_db("A");
    mysql_connect("$host", "$user2", "$pass2"); mysql_select_db("B"); 
   //host A = host B same host 
    $MySQL="Select username FROM A.members INSERT INTO B.members"; 
    $result= mysql_query($MySQL);

If you are connecting to the same host, you only need to make the connection once. And setting the default database using mysql_select_db("A"); should not be necessary because you are specifying which database to use in your statement.

The SQL for your insert should be:

INSERT INTO B.members (username) SELECT username FROM A.members

Check out the documentation for INSERT...SELECT .

create two connection and use it in query eg:

  $con = mysqli_connect("localhost","root","","db1");
        $con2 = mysqli_connect("localhost","root","","db2");
         $query1 = mysqli_query($con1,"SELECT * FROM tbl1 order by ID desc ");
         while($row = $query1 ->fetch_assoc())
      {

         $query2 = mysqli_query($con2,"insert into  tbl2 (fields) values('".$row['field
']."')");

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM