Last active
April 21, 2021 09:29
-
-
Save abdoulmouctard/27ceeaf2bb2635aaa3f0087f9e24a06d to your computer and use it in GitHub Desktop.
MYSQL TABLE ARCHIVER
This file contains 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 | |
/* ------------------------------------------ | |
* MYSQL TABLE ARCHIVER | |
* ------------------------------------------ | |
* This script use old versions of PHP. | |
* So you need to change mysqli connections | |
* by the new syntaxes (PDO, mysql) | |
* ------------------------------------------ | |
* php table_backup.php | |
------------------------------------------ */ | |
$host = ""; | |
$port = null; // USE DEFAULT MySQL PORT | |
$database = 'DB_NAME'; | |
$username = 'DB_USERNAME'; | |
$password = 'DB_PASSWORD'; | |
$tableName = 'CURRENT_TABLE_NAME'; | |
$newTableName = 'FUTURE_TABLE_NAME' . '_' . date("dmY"); | |
/** | |
* MySQL query executor | |
* | |
* @param resource $connection | |
* @param string $sql | |
* @return mixed | |
*/ | |
function execute_query($connection, $sql) | |
{ | |
$result = mysql_query($sql, $connection); | |
if (!$result) { | |
echo "\n \n " . mysql_error($connection) . "\n \n"; | |
} | |
return $result; | |
} | |
/** | |
* Rename DB Table [FROM_NAME] -> [TO_NAME] | |
* | |
* @param resource $from_name | |
* @param string $from_name | |
* @param string $to_name | |
* @return mixed | |
*/ | |
function rename_db_table($connection, $from_name, $to_name) | |
{ | |
execute_query($connection, "prepare stmt from (rename table $from_name to $to_name)"); | |
execute_query($connection, "execute stmt"); | |
execute_query($connection, "deallocate prepare stmt"); | |
} | |
$connection = @mysql_connect($host, $username, $password); | |
mysql_select_db($database, $connection); | |
$tmpTableName = $newTableName . "_tmp"; | |
execute_query($connection, "CREATE TABLE $tmpTableName LIKE $tableName"); | |
rename_db_table($connection, $tableName, $newTableName); | |
rename_db_table($connection, $tmpTableName, $tableName); | |
mysql_close($connection); | |
echo "DONE."; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment