Skip to content

Instantly share code, notes, and snippets.

@andronex
Created October 16, 2024 18:10
Show Gist options
  • Save andronex/c4257155053719ef7b6c212744bb1f4d to your computer and use it in GitHub Desktop.
Save andronex/c4257155053719ef7b6c212744bb1f4d to your computer and use it in GitHub Desktop.
Массовое переименование таблиц БД MySQL с помощью PHP скрипта версии 7.0+
<?php
$db_server = "localhost"; // hostname MySQL server
$db_username = "cl723w"; // username MySQL server
$db_password = "Wwe"; // password MySQL server
$db_name = "cl7"; // database name
$pattern = "a_"; // search string
$new_pattern = "b_"; // replacement string,
// can be empty
// login to MySQL server
$link = mysqli_connect( $db_server, $db_username, $db_password, $db_name);
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
// list all tables in the database containing the search pattern
$sql = "SHOW TABLES FROM `" . $db_name . "`";
$sql .= " LIKE '%" . $pattern . "%'";
$result = mysqli_query ( $link, $sql );
if (!$result)
{
die("Invalid query: " . mysqli_error( $link ));
}
$renamed = 0;
$failed = 0;
while ( $row = mysqli_fetch_array ($result) )
{
// rename every table by replacing the search pattern
// with a new pattern
$table_name = $row[0];
$new_table_name = str_replace ( $pattern, $new_pattern, $table_name);
$sql = "RENAME TABLE `" . $db_name . "`.`" . $table_name . "`";
$sql .= " TO `" . $db_name . "`.`" . $new_table_name . "`";
$result_rename = mysqli_query ( $link, $sql );
if ($result_rename)
{
echo "Table `" . $table_name . "` renamed to :`";
echo $new_table_name . "`.\n";
$renamed++;
}
else
{
// notify when the renaming failed and show reason why
echo "Renaming of table `" . $table_name . "` has failed: ";
echo mysqli_error( $link ) . "\n";
$failed++;
}
}
echo $renamed . " tables were renamed, " . $failed . " failed.\n";
// close connection to MySQL server
mysqli_close( $link );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment