【PHP】清空MySQL数据,索引重置

小破孩
2025-05-06 / 0 评论 / 17 阅读 / 正在检测是否收录...
<?php

// 定义排除表的常量
const EXCLUDE_TABLES = [
    'web_admin_company',
    'web_admin_func',
    'web_admin_role',
    'web_admin_user',
    'web_app_config',
    'web_china_city',
    'web_china_city_area',
    'web_china_city_backup',
    'web_company_config',
    'web_shop_category',
    'web_tppay',
//    'web_shop_goods_tmpserver',
];

class SomeClass
{
    public function truncateTables()
    {
        try {
            // 开启事务
            Db::startTrans();

            // 获取所有表名
            $tables = Db::query('SHOW TABLES');
            $tableNames = array_map('current', $tables);

            foreach ($tableNames as $tableName) {
                if (!in_array($tableName, EXCLUDE_TABLES)) {
                    // 使用参数化查询清空表并重置索引
                    Db::execute("TRUNCATE TABLE `$tableName`");
                    echo "表 {$tableName} 已清空<br>";
                }
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            // 记录错误日志
            error_log("发生错误: " . $e->getMessage());
            echo "发生错误: " . $e->getMessage();
        }
    }
}    
0

评论 (0)

取消