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

2023-07-24 21:20:22 浏览数 (2)

代码语言:javascript复制
// 数据库字段转驼峰法
$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 (thinkhelperStr::contains($t['Field'], '_')) {
            //dump($t);
            $col = thinkhelperStr::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);

0 人点赞