Select from a database and insert into a different database

Here is an example of how to select some data from a table on one database and insert into a table of a different database. I am assuming that you are using the same mysql connection.

The MySQL USE command is used to select the appropriate database at the appropriate time. database1 is where the data is being selected from and database2 is where it is inserted to.

  1. $handle = mysql_connect("localhost", "username", "password") or die(mysql_error());
  2.  
  3. mysql_query("USE database1",$handle);
  4. $query = "SELECT * FROM table";
  5. $result = mysql_query($query);
  6.  
  7. while ($data = mysql_fetch_object($result)){
  8. $variable1 = $data->column1;
  9. $variable2 = $data->column2;
  10.  
  11. mysql_query("USE database2",$handle);
  12. $sql = "INSERT INTO table2 SET
  13. col1 = '$variable1',
  14. col2 = '$variable2'";
  15. if (!mysql_query($sql)) {
  16. echo '<p>Error adding data into database: ' . mysql_error() . '</p>';
  17. }
  18. mysql_query("USE database1",$handle);
  19.  
  20. }

Conquer Drupal 8 Module Development

Don't struggle to conquer Drupal 8 module development. Action packed lessons where you will work along building your own real world modules.

20% launch discount available now!

Find out more


Comments

thanks!!!

Thanks man, not a lot of info to be found around this, so very useful!

Tank u so much.Its very cleared and simple method

Add new comment