Hongmu Notes
Home Language Notes PHP modify data table prefix
Language Notes PHP PHP and mysql

PHP modify data table prefix

PHP modify data table prefix

For a database with just one or two tables, manual modification is manageable!

However, I have over 260 data tables – manually processing them would be absolutely exhausting!

At this point, PHP can be used for batch modification!

To change the table prefix for your MySQL database, follow these steps:

  1. Connect to a MySQL database.
  2. Retrieve all table names from the database.
  3. Iterate through each table and replace its name with the new prefix.
  4. Execute an ALTER TABLE statement for each table to change its name to the new name.

Here is a PHP code example that can be used to replace the table prefix in a MySQL database:

 隐藏内容:会员可查看
<?php

// 数据库连接信息
$host = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
$old_prefix = "old_prefix_";  // 旧前缀
$new_prefix = "new_prefix_";  // 新前缀

// 创建数据库连接
$conn = new mysqli($host, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 查询数据库中所有的表名
$sql = "SHOW TABLES";
$result = $conn->query($sql);

// 遍历每个表,为其名称替换新的前缀
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $old_table_name = $row["Tables_in_$dbname"];
        $new_table_name = str_replace($old_prefix, $new_prefix, $old_table_name);

        // 执行 ALTER TABLE 语句,将表名修改为新的名称
        $sql = "ALTER TABLE $old_table_name RENAME TO $new_table_name";
        if ($conn->query($sql) === TRUE) {
            echo "表 $old_table_name 重命名为 $new_table_name 成功!<br>";
        } else {
            echo "表 $old_table_name 重命名为 $new_table_name 失败: " . $conn->error . "<br>";
        }
    }
} else {
    echo "没有找到任何数据表!";
}

// 关闭数据库连接
$conn->close();
?>

$old_prefix$new_prefix Replace the prefix with the one you need, then save the code as a PHP file and execute it. Note that executing this operation may take some time, depending on the size of your database.

Absolutely perfect!

Here is a function.

 隐藏内容:会员可查看
/**
 * 修改 MySQL 数据库中数据表的前缀
 *
 * @param string $old_prefix 旧前缀
 * @param string $new_prefix 新前缀
 * @param string $db_host 数据库主机名
 * @param string $db_user 数据库用户名
 * @param string $db_password 数据库密码
 * @param string $db_name 数据库名
 *
 * @return bool 操作是否成功
 */
function changeTablePrefix($old_prefix, $new_prefix, $db_host, $db_user, $db_password, $db_name) {
    // 创建 MySQL 数据库连接
    $conn = new mysqli($db_host, $db_user, $db_password, $db_name);

    // 检查连接是否成功
    if ($conn->connect_error) {
        die("连接失败: " . $conn->connect_error);
    }

    // 获取所有数据表名
    $result = $conn->query("SHOW TABLES");

    // 遍历数据表名
    while ($row = $result->fetch_assoc()) {
        // 获取当前数据表名
        $table_name = $row['Tables_in_' . $db_name];

        // 如果数据表名以旧前缀开头,那么修改该数据表名
        if (strpos($table_name, $old_prefix) === 0) {
            $new_table_name = $new_prefix . substr($table_name, strlen($old_prefix));
            $conn->query("RENAME TABLE $table_name TO $new_table_name");
        }
    }

    // 关闭 MySQL 数据库连接
    $conn->close();

    // 返回操作结果
    return true;
}

This function accepts six parameters; the first two parameters old_prefixnew_prefix The first two parameters represent the old prefix and the new prefix to be replaced, respectively; the remaining four parameters are optional. db_hostdb_userdb_passworddb_name These represent the host name, username, password, and database name of the MySQL database, respectively. The function returns a boolean value indicating whether the operation was successful.

Within the function, first create a MySQL database connection, then use it. SHOW TABLES The command retrieves all table names from the current database and iterates over these table names. For each table name, the function checks whether it begins with the old prefix; if so, it uses it. RENAME TABLE The command replaces the name of the data table with the new prefix concatenated to the portion of the original prefix that remains after the new prefix. Finally, the function closes the MySQL database connection and returns the result of the operation.

Please note that modifying the prefix of a data table is a destructive operation; therefore, before running this function, be sure to back up your database and carefully verify the prefix you intend to modify to ensure that you are not altering any data tables that do not require modification.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232
PHP special character escaping and restoration

PHP special character escaping and restoration Language Notes PHP PHP collection PHP and mysql

Escape character is a special character constant. Escape characters are backslashed " & quot; At the beginning, followed by one or more characters. The escaped character has a specific meaning, which is different from the original meaning of the character, so it is called "escaped" character. The use of escape characters 1: turn ordinary characters into special purposes, such as back key and enter key. 2. Used to convert a character with special meaning back to its original meaning. 3. Before data is written into the database, escape characters (function …
👁 181
mysqli in PHP

mysqli in PHP Language Notes PHP PHP collection PHP and mysql

The `mysqli_num_rows()` function is exclusively used with `SELECT` query methods, whereas the `mysqli_affected_rows()` function returns the number of rows affected by the previous SQL statement across the entire database; this function is primarily used with `INSERT`, `UPDATE`, and `DELETE` operations.
👁 146

Recommended reading

(Adaptive Mobile Version) Responsive Unified Front Government Agency Website PBootCMS Template – Red Government Agency Website Source Code Download: 0163

(Adaptive Mobile Version) Responsive Unified Front Government Agency Website PBootCMS Template – Red Government Agency Website Source Code Download: 0163 Practical Collection pbootcms Template

This set of adaptive mobile-friendly, responsive PbootCMS website templates designed for government and public institution websites features a red color scheme. The design style is solemn and authoritative, aligning with the brand image requirements for government and public entities. It enables government departments, public institutions, or social organizations to establish official information publishing platforms. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s...
👁 59
Responsive freight logistics transportation website template – 0996

Responsive freight logistics transportation website template – 0996 Practical Collection Yiyou template

An EyouCMS responsive website template designed specifically for the freight and logistics industry. Its efficient, modern design effectively showcases logistics services, delivery networks, and corporate strength. This template helps logistics companies present their brand online and attract both e-commerce and corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 61
(Adaptive mobile version) Desulfurization equipment website template; Pressure vessel website source code download – 1145

(Adaptive mobile version) Desulfurization equipment website template; Pressure vessel website source code download – 1145 Practical Collection pbootcms Template

A desulfurization equipment and pressure vessel website template compatible with both PC and WAP devices. The professional industrial design is ideal for showcasing desulfurization equipment, pressure vessel products, and project cases. It enables environmental protection equipment manufacturers to showcase their products online and attract clients from the power and chemical industries. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 60
(Adaptive Mobile Version) Responsive Marketing-Driven Constant Temperature and Humidity Controller – Environmental Equipment Website pbootCMS Template; Blue Marketing-Driven Air Conditioning Equipment Website Source Code Download – 0164

(Adaptive Mobile Version) Responsive Marketing-Driven Constant Temperature and Humidity Controller – Environmental Equipment Website pbootCMS Template; Blue Marketing-Driven Air Conditioning Equipment Website Source Code Download – 0164 Practical Collection pbootcms Template

An adaptive mobile-responsive, marketing-oriented constant temperature and humidity control unit, paired with a PbootCMS template for environmental equipment – featuring a blue color scheme. This professional, tech-driven design is ideal for showcasing precision environmental control equipment and technical solutions. It helps environmental equipment companies highlight their product advantages online and attract high-end clients such as laboratories and manufacturing facilities. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extract...
👁 30
Responsive automotive engine parts website template 0997

Responsive automotive engine parts website template 0997 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the automotive engine and accessories industry. Its professional automotive design style enables effective display of engine products, automotive parts, technical specifications, and maintenance services. It helps automotive parts enterprises showcase their products online and attract customers from the automotive aftermarket. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | Eyou...
👁 44
(PC+WAP) human resources website template employment agency website source code download 1146

(PC+WAP) human resources website template employment agency website source code download 1146 Practical Collection pbootcms Template

A human resources and employment agency PbootCMS website template that supports PC and WAP. The design style is professional and stable, suitable for human resources companies and employment agencies to display services and positions. Helps human resources organizations to build online recruitment service platforms. Template display Installation instructions Website backend: /admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles...
👁 62