Skip to content

Instantly share code, notes, and snippets.

@zacbrac
Last active September 25, 2015 22:32
Show Gist options
  • Save zacbrac/80a42905758dcb98ac36 to your computer and use it in GitHub Desktop.
Save zacbrac/80a42905758dcb98ac36 to your computer and use it in GitHub Desktop.
TableTransferrerAllows you to transfer tables from one db to another with minimal effort.No file handling necessary, you only need the table names, and a connection from db 1 to db 2.
<?php
/*
* TableTransferrer
*
* Allows you to transfer tables from one db to another with minimal effort.
* No file handling necessary, you only need the table names, and a connection from db 1 to db 2.
*
*/
class TableTransferrer {
public function getTable(PDO $db, $table_name) {
$table = $db->prepare('SELECT * FROM ' . $table_name);
$table->execute();
return $table->fetchAll(PDO::FETCH_NUM);
}
public function getTableColumns(PDO $db, $table_name) {
$columns = [];
$table = $db->prepare('EXPLAIN ' . $table_name);
$table->execute();
$result = $table->fetchAll();
foreach ($result as $row) {
$columns[] = $row['Field'];
}
return $columns;
}
public function insertTable(PDO $db, $table_data) {
$table_name = $table_data[0];
$table_columns = implode(', ', $table_data[1]);
$table_values = [];
foreach ($table_data[2] as $row) {
$table_values[] = '(\'' . implode('\',\'', $row) . '\')';
}
$table_values = implode(',', $table_values);
$table = $db->prepare('INSERT INTO ' . $table_name . ' (' . $table_columns . ') VALUES ' . $table_values);
return ($table->execute() ? true : false);
}
public function transferTables($table_names, $db_1, $db_2) {
$table_values = $outcomes = [];
foreach ($table_names as $table) {
$table_values[] = [$table, $this->getTableColumns($db_1, $table), $this->getTable($db_1, $table)];
}
foreach ($table_values as $table) {
$outcomes[] = $this->insertTable($db_2, $table);
}
return $outcomes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment