How to safely migrate data between databases in MySQL with PHP
I saw many people using lots of complex methods in attempt to move data between databases and file systems.
One of the most frequent methods is storing sequential data records in CSV, TSV, XML, or other formats. Obviously, each syntax requires specific escaping algorithms, a fact that most of times is omitted or forgotten by developer.
The last time I had to move data between two different instances of MySQL from two different sites I followed the approach:
- Select the database records and put them in an object (array);
- serialize the array;
- encode the array in base64 to ensure the text needs no escaping algorithm;
- copy the text on a support (file, ftp, mail, etc.);
- decode the array from base64 to native format;
- deserialize the array;
- take each record and save it to the database.
Some of the advantages are:
- you don't transfer database records, but business objects;
- if you have complex relations or fields, they just get wrapped, irrelevant on the database representation.
A code example is in sample.php.
And the result will be similar to
sample.txt.
<?php $dbConnection=BO::getConnection();
$recordSet=$dbConnection->SELECT('select timeStamp, uuid, author from articleComment where oid<3');
echo("<p/>var_dump: ");
var_dump($recordSet);
$serialization=serialize($recordSet);
echo("<p/>Serialization: $serialization");
$base64=base64_encode($serialization);
echo("<p/>Base 64 final result: $base64");
echo("<p/>Deserialization stage - running on the target machine");
$decodedValue=base64_decode($base64);
echo("<p/>Decoded string: $decodedValue");
$deserializedObject=unserialize($decodedValue);
echo("<p/>Deserialized object: ");
var_dump($deserializedObject);