Trying to copy a database into a new database, using a PHP script that runs SQL queries on a MySQL server. The code I have sofar is:
$dbh->exec("CREATE DATABASE IF NOT EXISTS $new_news CHARACTER SET UTF8;");
$results = $dbh->query("SHOW TABLES FROM $old_news");
$table_list = $results->fetchAll(PDO::FETCH_NUM);
foreach($table_list as $table_row){
foreach($table_row as $table){
$results = $dbh->query("SELECT table_type FROM information_schema.tables where table_schema = '$old_news' and table_name = '$table'");
$table_type = $results->fetch(PDO::FETCH_ASSOC);
$table_type = $table_type['table_type'];
if($table_type == 'BASE TABLE'){
echo "Creating table $table and populating...\n";
$dbh->exec("CREATE TABLE $new_news.$table LIKE $old_news.$table");
$dbh->exec("INSERT INTO $new_news.$table SELECT * FROM $old_news.$table");
}else if($table_type == 'VIEW'){
//echo "Creating view $table...\n";
//$dbh->exec("CREATE VIEW $new_news.$table LIKE $old_news.$table");
echo "$table is a view, which cannot be copied atm\n";
}else{
echo "Skipping $table_type $table, unsupported type\n";
}
}
}
This currently looks at all tables in $old_news, finds the table type in the information_schema, and creates an identical table in $new_news depending on the type. For tables, it creates the table structure the same, then 'INSERT INTO SELECT' to fill them.
How do you copy a view without mysqldump the entire database?
You can use INFORMATION_SCHEMA.VIEWS to see the view definition, or SHOW CREATE VIEW for the whole statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With