简体   繁体   中英

how to select from one database and insert into another Database in a Single query with different Database connections in php

mysql_connect("localhost","root","");
mysql_select_db("database1");
mysql_query("INSERT INTO database2.categories (category_name,description,group_id,created)
  SELECT table1.name, table1.description, 12, UNIX_TIMESTAMP()
  FROM GiveArang_categories Where `p_id`= '225' ");

I need to insert data into the second database which is selected from the first database. Both databases have different connections. It needs to done in php in a single query .

The only way of doing this (that I know of) is by two separate connections.

Something like this:

mysql_connect("localhost","root","");
mysql_select_db("database2");
mysql_query("INSERT INTO database2.categories (category_name,description,group_id,created)");
mysql_close();

mysql_connect("localhost","root","");
mysql_select_db("database1");
mysql_query("SELECT table1.name, table1.description, 12, UNIX_TIMESTAMP() FROM GiveArang_categories Where `p_id`= '225' ");
mysql_close();

Unfortunately there's no Oracle dblink (which is what you need to connect to another database in a single query in Oracle Database) equivalent in MySql.

See also this for further information.

You can pop a MySQL Proxy to sit between your server and database boxes which will allow you to treat them as if they are on the same server. You can then use databasename.tablename within your query to identify your different databases via the same connection.

If both databases are on the same mysql-server you can note it like this:

mysql_connect("localhost","root","");
mysql_query("INSERT INTO database2.categories (category_name,description,group_id,created)
  SELECT database1.table1.name, database1.table1.description, 12, UNIX_TIMESTAMP()
  FROM database1.GiveArang_categories Where database1.GiveArang_categories.p_id= '225' ");

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