您现在的位置是:首页 > 一键转换mysql数据库字段名下划线为驼峰法

一键转换mysql数据库字段名下划线为驼峰法

默认 2020-03-08 00:00 2546人围观 来源:原创
mysql  
简介虽然出于大小写问题的混乱,mysql数据库最好用下划线法命名字段,但是一些场景实在需要驼峰法可以用本文方法一键转换。
// 数据库字段转驼峰法
$mysql_conn = mysqli_connect(
        config('database.hostname'),
        config('database.username'),
        config('database.password')
    ) or die("Mysql连接失败!");
// 获取表
$database = config('database.database');
mysqli_select_db($mysql_conn, $database);
mysqli_query($mysql_conn, 'SET NAMES utf8');
$table_result = mysqli_query($mysql_conn, 'show tables');
$tables = array();
while ($row = mysqli_fetch_array($table_result)) {
    $tables[]['tableName'] = $row[0];
}
foreach ($tables as $k => $v) {
    // 表结构
    $sql = "SHOW FULL COLUMNS FROM " . $v['tableName'] . " ";
    $table_result = mysqli_query($mysql_conn, $sql);
    while ($t = mysqli_fetch_array($table_result)) {
        if (\think\helper\Str::contains($t['Field'], '_')) {
            //dump($t);
            $col = \think\helper\Str::camel($t['Field']);
            if ($t['Null'] == 'NO') {
                $isNull = 'NOT NULL';
            } else {
                $isNull = 'NULL';
            }
            $default = "DEFAULT '" . $t['Default'] . "'";
            if ($t['Type'] == 'text' || $t['Type'] = 'longtext') {
                $isNull = '';
                $default = '';
            }
            $sql1 = "ALTER TABLE `" . $v['tableName'] . "` CHANGE `" . $t['Field'] . "` `" . $col . "` " . $t['Type'] . " " . $isNull . " " . $default . " COMMENT '" . $t['Comment'] . "';";
            mysqli_query($mysql_conn, $sql1);
        }
    }
}
mysqli_close($mysql_conn);
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cn0udci9ym88

文章评论