Created
July 3, 2013 15:23
-
-
Save yireo/5919293 to your computer and use it in GitHub Desktop.
PHP-script to rename MySQL database tables in a MySQL database - for instance when using Joomla!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$database_host = 'localhost'; // Database hostname | |
$database_user = 'root'; // Database username | |
$database_password = ''; // Database password | |
$database_name = 'myjoomla'; // Database name | |
$new_table_prefix = 'zkl_'; // New table prefix | |
$old_table_prefix = 'jos_'; // Old table prefix (optional) | |
$test = false; // Test-run (true or false) | |
// NO NEED TO EDIT BELOW THIS LINE | |
// Login to the database server | |
$db = mysql_connect($database_host, $database_user, $database_password) or die('MySQL connect failed'); | |
// Connect to the database | |
mysql_select_db($database_name) or die('Failed to select database'); | |
// Get a listing of all tables | |
$query = "SHOW TABLES"; | |
$result = mysql_query($query) or die('SHOW TABLES failed'); | |
// Loop through all tables | |
while($row = mysql_fetch_array($result)) { | |
$old_table = $row[0]; | |
// Preliminary check: Is the old table prefix correct? | |
if(!empty($old_table_prefix) && !preg_match('/^'.$old_table_prefix.'/', $old_table)) { | |
echo "Table $old_table does not match prefix $old_table_prefix<br/>\n"; | |
continue; | |
} | |
// Preliminary check: Is the old table prefix the same as the new one? | |
if(preg_match('/^'.$new_table_prefix.'/', $old_table)) { | |
echo "Table $old_table already done<br/>\n"; | |
continue; | |
} | |
// Construct the new table prefix | |
if(!empty($old_table_prefix)) { | |
$new_table = preg_replace('/^'.$old_table_prefix.'/', $new_table_prefix, $old_table); | |
} else { | |
$new_table = $new_table_prefix.$old_table; | |
} | |
// Rename the actual table | |
echo "Renaming $old_table to $new_table<br/>\n"; | |
$query = "RENAME TABLE `$old_table` TO `$new_table`"; | |
mysql_query($query); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also put the script explained at http://geeksww.com/tutorials/database_management_systems/mysql/administration/how_to_rename_mysql_db_name_by_moving_tables.php and run it through PHP exec() or similar function.