Skip to content
Advertisement

How clone all data from one database to another one in Codeigniter

I am going to move all data from the live stage database into another new database. The project is based on Codeignitor. For now I am using dump file but it’s really slow to handle them.

$temp_path = './db/dump/old_backup.sql';

// Create temporary table
echo "Preparing temporary database ..... n";
$this->createTemporarDB();

// Make Dump from live db
echo "Preparing backup from live database ..... n";
$backup = $this->exportDumpFromDB('default', 'old_backup.sql');
write_file($temp_path, $backup, 'w+');

$this->new_db = $this->load->database('new_db', true);
$temp_line = '';
$lines = file('./db/dump/old_backup.sql');

foreach ($lines as $line) {
    if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 1) == '#') {
        continue;
    }
    $temp_line .= $line;
    // Display percentage of temp data
    if (substr(trim($line), -1, 1) == ';') {
        $this->temp_db->query($temp_line);
        $temp_line = '';
    }
    $index++;
}

Is there any best method to solve my issues( latency issue, I need to speed up ). Thank you.

Advertisement

Answer

I fixed this issue. Attached my approach here.

$tables = $this->db->query("SHOW TABLES FROM [old db name]")->result_array();
$this->temp_db = $this->load->database[new db name]', true);
foreach ($tables as $key => $val) {
   $this->temp_db->query('CREATE TABLE ' . $val['Tables_in_squirrel'] . ' LIKE [old db name].' . $val['Tables_in_squirrel']);
   $this->temp_db->query('INSERT ' . $val['Tables_in_[old db name]'] . ' SELECT * FROM squirrel.' . $val['Tables_in_squirrel']);
  }
}

This is the code based on Codeigniter.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement