Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use a MySQL Query to Completely Create a Copy of the Database

Tags:

php

mysql

I have a LIVE version of a MySQL database with 5 tables and a TEST version.

I am continually using phpMyAdmin to make a copy of each table in the LIVE version to the TEST version.

Does anyone have the mysql query statement to make a complete copy of a database? The query string would need to account for structure, data, auto increment values, and any other things associated with the tables that need to be copied.

Thanks.

like image 703
H. Ferrence Avatar asked May 13 '11 19:05

H. Ferrence


People also ask

How do you duplicate a database?

On either the source or destination SQL Server instance, launch the Copy Database Wizard in SQL Server Management Studio from Object Explorer and expand Databases. Then right-click a database, point to Tasks, and then select Copy Database.


2 Answers

Ok, after a lot of research, googling, and reading through everyone's comments herein, I produced the following script -- which I now run from the browser address bar. Tested it and it does exactly what I needed it to do. Thanks for everyone's help.

<?php
function duplicateTables($sourceDB=NULL, $targetDB=NULL) {
    $link = mysql_connect('{server}', '{username}', '{password}') or die(mysql_error()); // connect to database
    $result = mysql_query('SHOW TABLES FROM ' . $sourceDB) or die(mysql_error());
    while($row = mysql_fetch_row($result)) {
        mysql_query('DROP TABLE IF EXISTS `' . $targetDB . '`.`' . $row[0] . '`') or die(mysql_error());
        mysql_query('CREATE TABLE `' . $targetDB . '`.`' . $row[0] . '` LIKE `' . $sourceDB . '`.`' . $row[0] . '`') or die(mysql_error());
        mysql_query('INSERT INTO `' . $targetDB . '`.`' . $row[0] . '` SELECT * FROM `' . $sourceDB . '`.`' . $row[0] . '`') or die(mysql_error());
        mysql_query('OPTIMIZE TABLE `' . $targetDB . '`.`' . $row[0] . '`') or die(mysql_error());
    }
    mysql_free_result($result);
    mysql_close($link);
} // end duplicateTables()
duplicateTables('liveDB', 'testDB');
?>
like image 174
H. Ferrence Avatar answered Oct 10 '22 01:10

H. Ferrence


Depending on your access to the server. I suggest using straight mysql and mysqldump commands. That's all phpMyAdmin is doing under the hood.

like image 27
Jason McCreary Avatar answered Oct 10 '22 02:10

Jason McCreary