編碼大全
可參考我之前的文章:
快速理解ASCII溜畅、GBK捏卓、Unicode、UTF-8慈格、ANSI
批量修改
注意這是DDL操作怠晴,操作過(guò)程會(huì)鎖表(元數(shù)據(jù)鎖),平均1秒能夠轉(zhuǎn)碼3張表(數(shù)據(jù)量不大)浴捆。
親測(cè)操作過(guò)后沒(méi)有數(shù)據(jù)異常蒜田,推薦執(zhí)行前備份。
//接手一些老項(xiàng)目选泻,需要修改編碼冲粤。
$host = '';
$db = '';
$user = '';
$pass = '';
$charset = 'utf8mb4';
$collate = 'utf8mb4_unicode_ci';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db;charset=$charset", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 從information_schema獲取所有的表名
$stmt = $pdo->query("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = '$db'");
$tables = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
// 遍歷所有的表并修改其編碼
foreach ($tables as $table) {
$sql = "ALTER TABLE `$table` CONVERT TO CHARACTER SET $charset COLLATE $collate;";
$pdo->exec($sql);
echo "{$table} ====> {$charset}/{$collate}" . PHP_EOL;
}
} catch (PDOException $e) {
die("MySQL連接失敗" . $e->getMessage());
}
最后別忘了執(zhí)行數(shù)據(jù)庫(kù)本身的轉(zhuǎn)碼操作。
ALTER DATABASE my_database CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;