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());
  3. mysql_query("USE database1",$handle);
  4. $query = "SELECT * FROM table";
  5. $result = mysql_query($query);
  7. while ($data = mysql_fetch_object($result)){
  8. $variable1 = $data->column1;
  9. $variable2 = $data->column2;
  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);
  20. }



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

New comments for this tutorial have been turned off.