35

I need to copy a table from one database to another. This will be a cronjob. Which one is the best way to do it? PHP script or Shell Script. The problem with PHP, both databases has different usernames and passwords so I can't do it like this.

CREATE TABLE db1.table1 SELECT * FROM db2.table1

Should I just connect first DB get all records and insert all to new database using WHILE loop or there is a better way?

I prefer a shell script to do this instead of PHP script.

Thanks

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
Ergec
  • 11,608
  • 7
  • 52
  • 62

12 Answers12

60

If you need to copy the table on the same server you can use this code:

USE db2;

CREATE TABLE table2 LIKE db1.table1;

INSERT INTO table2  
    SELECT * FROM db1.table1;

It's copy+pasted from here: codingforums.com

It's not my solution, but I find it useful.

Radu Damian
  • 1,051
  • 10
  • 8
37

I'd dump it. Much less complicated than anything PHP based.

mysqldump -u user1 -ppassword1 databasename > dump.sql
mysql -u user2 -ppassword2 databasename < dump.sql

MySQL reference: 4.5.4. mysqldump — A Database Backup Program

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 8
    Since I want to transfer only one table, I guess with a little bit mod this will work mysqldump -u user1 -ppassword1 --add-drop-table databasename tablename > dump.sql thank you – Ergec Oct 14 '10 at 11:35
  • If you use phpmyadmin, then it will be better. – gautamlakum Oct 14 '10 at 13:22
  • 8
    You can even pipe it through: `mysqldump --user=root --password=remote_password the_database_name | mysql --user=root --password=local_password the_database_name`; usually this may be done from server to server using SSH-port-forwarding: `ssh -f -N -L 3307:localhost:3306 nmmn` (nmmn is one of my SSH-shortcuts, use a server-name+port instead); @Ergec for multiple tables use the param `--tables table1 table2` – feeela Aug 30 '11 at 21:50
  • Personally, I would cat the file back into mysql – Daryl Gill May 06 '13 at 15:29
  • also noteworthy to add that there is no space between `-p` and the password. Some tend to think it is a typo as well as if your password contains any special characters you will need to accent them with `\\` – Cesar Bielich Aug 07 '20 at 22:30
36
mysqldump -u user1 -ppassword1 databasename TblName | mysql -u user2 -ppassword2 anotherDatabase

It all can be done in a single command.

shantanuo
  • 31,689
  • 78
  • 245
  • 403
7
$L1 = mysql_connect('localhost', 'user1', 'pass1');
$DB1 = mysql_select_db('database1', $L1);   

$L2 = mysql_connect('localhost', 'user2', 'pass2');
$DB2 = mysql_select_db('database2', $L2);   

$re=mysql_query("SELECT * FROM table1",$L1);
while($i=mysql_fetch_assoc($re))
{
    $u=array();
    foreach($i as $k=>$v) if($k!=$keyfield) $u[]="$k='$v'";
    mysql_query("INSERT INTO table2 (".implode(',',array_keys($i)).") VALUES ('".implode("','",$i)."') ON DUPLICATE KEY UPDATE ".implode(',',$u),$L2) or die(mysql_error());
}

user1, pass1, database1, table1 reffers to initial table user2, pass2, database2, table2 reffers to copied table $keyfield is the primary key of table

user3637009
  • 79
  • 1
  • 1
7

One liner with different servers

mysqldump -h host1 -u user1 -ppassword1 databasename TblName | mysql -h host2 -u user2 -ppassword2 anotherDatabase
Juergen Schulze
  • 1,515
  • 21
  • 29
5
CREATE TABLE db_target.cloned_table 
SELECT * 
FROM db_source.source_table;
Fury
  • 4,643
  • 5
  • 50
  • 80
5

Phpmyadmin has inbuilt functionality to copy tables from one database to another. Otherwise you can go with Pekka or export table then import table.

gautamlakum
  • 11,815
  • 23
  • 67
  • 90
  • 1
    IIRC, the inbuilt functionality will work only if the same user has access to both databases. – Pekka Oct 14 '10 at 13:52
3

I'll put this answer up for anyone else looking for help.

If you don't have access to SSH then you can use PhpMyAdmin.

Simply:

  1. browse to the table you want to move
  2. Click the Operations tab
  3. Use the MOVE or COPY to database function

If you come across privilege problems, you can temp grant a user Global permissions or add the same user to both databases.

1
exec('mysqldump --user=username --password="password" --host=hostname --database=database table1 table2 > databasedump.sql');

exec('mysql --user=username --password="password" --host=hostname --database=database < databasedump.sql');
D.Y.
  • 149
  • 2
  • 7
0
insert into dest.table select * from orginal.table;
unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62
0

use <from database>

create table <to database.new name> as (select * from <table to copy>);
e-sushi
  • 13,786
  • 10
  • 38
  • 57
  • 1
    Welcome to stackoverflow. I think your answer got messed up. Please try to reformat it marking it as code. – Simon H Jul 18 '13 at 22:16
  • 1
    As it stands this answer makes little sense. Please add some explanaation, and correct the snippet you've posted –  Jul 18 '13 at 22:18
-1

As it seems that nobody answered the initial question actually, here is my PHP script to backup a table from a remote MySQL server to a local MySQL server:

function backup_remote_table (
    $remote_db_host, $remote_login, $remote_password, $remote_db_name, $remote_table_name,
    $local_db_host, $local_login, $local_password, $local_db_name, $local_table_name
) {
    // Generating names with time stamps for local database and/or local table, if not available
    if ($local_table_name) {
        $applied_local_table_name = $local_table_name;
    } else {
        $applied_local_table_name = $remote_table_name;
    }
    if ($local_db_name) {
        $applied_local_db_name = $local_db_name;
        if (!$local_table_name) {
          $applied_local_table_name .= date_format(date_create(), '_Y_m_d_H_i_s');
        }
    } else {
        $applied_local_db_name = $remote_db_name . date_format(date_create(), '_Y_m_d_H_i_s');
    }

    // Local server connection
    $local_db_server = mysql_connect($local_db_host, $local_login, $local_password);
    $local_db_server = mysql_query("CREATE DATABASE IF NOT EXISTS " . $applied_local_db_name, $local_db_server);
    mysql_select_db($applied_local_db_name, $local_db_server);

    // Remote server connection
    $remote_db_server = mysql_connect($remote_db_host, $remote_login, $remote_password);
    mysql_select_db($remote_db_name, $remote_db_server);

    // Getting remote table data
    $result_remote_table_info = mysql_query("SHOW CREATE TABLE " . $remote_table_name, $remote_db_server);
    $remote_table_info = mysql_fetch_array($result_remote_table_info);
    $remote_table_description = substr($remote_table_info[1], 13);

    // Creating local table
    $sql_new_table = "CREATE TABLE IF NOT EXISTS " . $applied_local_db_name . "." . $remote_table_description;
    mysql_query($sql_new_table, $local_db_server);

    // Getting all records of remote table
    $result_remote_table_data = mysql_query("SELECT * FROM " . $table_name, $remote_db_server);
    while ($remote_table_row = mysql_fetch_array($result_remote_table_data, MYSQL_ASSOC)){
        // Browsing records of remote table
        $sql_new_row = "INSERT INTO $applied_local_db_name.$applied_local_table_name (".implode(", ",array_keys($remote_table_row)).") VALUES (";
        $extra_sql = "";
        foreach (array_values($remote_table_row) as $value) {
            if ($extra_sql != "") {
                $extra_sql .= ",";
            }
            $extra_sql .= "'";
            $extra_sql .= mysql_real_escape_string($value);
            $extra_sql .= "'";
        }
        $sql_new_row .= $extra_sql . ")";
        // Adding record to local table
        $result_new_table_row = mysql_query($sql_new_row, $local_db_server);
    }
    mysql_free_result($result_remote_table_data);

    return;
}

The solution above is not mine, I got it here, with minor changes.