Iain Wood
Iain Wood

Reputation: 43

Copy a mysql database from one server to another PHP cron Job automated

Ok first off this is not a backup job, and I know about using phpmyadmin and so on.

What I have is a Live server and a TEST server, People work on the live one, constantly modifying it. I want the database on the LIVE server to be copied to the TEST server every night.

Does anyone have a php script I could run either to copy down the whole thing (or at least specific tables)? I'm not that confident with using the command line so if there is a way of doing it that way I could do with some pretty specific instructions :P

I have dug around but everyone seems to be suggesting doing it manually or by using third party tools.

Any help much appreciated.

Upvotes: 0

Views: 6802

Answers (2)

gamesmad
gamesmad

Reputation: 409

Drop the test tables -

DROP TABLE testdata;

And then recreate them as copies of the live tables -

CREATE TABLE testdata LIKE livedata;
INSERT INTO testdata SELECT * FROM livedata;

This could be done through PHP like this -

<?php

$host = '127.0.0.1';
$dbname = 'database'
$user = 'user';
$pass = 'pass';

try {  

  $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  

}

catch(PDOException $e) { 

    echo $e->getMessage(); 

}

$STH = $DBH->('DROP TABLE testdata');
$STH->execute();

$STH = $DBH->('CREATE TABLE testdata LIKE livedata');
$STH->execute();

$STH = $DBH->('INSERT INTO testdata SELECT * FROM livedata');
$STH->execute();

$DBH = null;

?>

You can add extra tables as required, but in my example it will make a table called testdata that mirrors the table called livedata.

Then set up a cron job to fire the script when required -

php /path/to/script.php

Upvotes: 0

Hackerman
Hackerman

Reputation: 12295

You could do something like this:

In your mysql host machine:

1- Create a .sh file
2- Inside of this sh, put:
 - mysqldump -u myuser -p mypass mydatabasename > mydumpfile.sql
 - scp mydumfile.sql user@remote_host:remote_dir
3- Add that sh to a cron Job, to a daily execute
   (or something that meets your requeriments)

In the remote machine:

1- One sh script that look for a file(mysqldumpfile.sql) in the specific dir
2- This line : mysql -u remotemysqluser -p remotemysqlpass database < mydumpfile.sql
3- rm mydumpfile.sql
4- Add this sh on a daily cron 1 or two hours past the host cron.

Upvotes: 3

Related Questions