Script to convert MySQL collation from utf8mb4 to utf8

May 11, 2015

I ran into a strange situation with WordPress where the MySQL server did not support utf8mb4. I needed to quickly convert the tables back to utf8 to get the site running again.

Though this script does work I highly recommend if you are running WordPress that you upgrade your MySQL server to support utf8mb4 for security. WordPress made this change to fix a security vulnerability introduced by The Trojan Emoji.

[bash]
DB="your_database_name"
USER="your_db_user"
PASS="your_db_pass"
(
echo ‘ALTER DATABASE `’"$DB"’` CHARACTER SET utf8 COLLATE utf8_general_ci;’
mysql -p$PASS -u $USER "$DB" -e "SHOW TABLES" –batch –skip-column-names \
| xargs -I{} echo ‘ALTER TABLE `'{}’` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;’
) \
| mysql -p$PASS -u $USER "$DB"
[/bash]