Skip to content

Instantly share code, notes, and snippets.

@andsens
Created October 3, 2012 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andsens/3826286 to your computer and use it in GitHub Desktop.
Save andsens/3826286 to your computer and use it in GitHub Desktop.
Converts an entire database to utf-8. Handy when you forgot to set default_encoding etc. in my.cnf
#/usr/bin/php
<?php
$mysqli = new mysqli('hostname', 'username', 'password');
$result = $mysqli->query(
"SELECT `TABLE_SCHEMA`, `TABLE_NAME` FROM `information_schema`.`TABLES`
WHERE
`TABLE_COLLATION` != 'utf8_general_ci'
AND `TABLE_SCHEMA` != 'mysql'
AND `TABLE_SCHEMA` != 'information_schema'");
while($row = $result->fetch_array()) {
$tableSchema = $row['TABLE_SCHEMA'];
$tableName = $row['TABLE_NAME'];
$mysqli->query(
"ALTER TABLE `$tableSchema`.`$tableName`
CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci") or die('Error: '.$mysqli->error);
echo "Converted `$tableSchema`.`$tableName`\n";
}
$result = $mysqli->query(
"SELECT `SCHEMA_NAME` FROM `information_schema`.`SCHEMATA`
WHERE
`DEFAULT_CHARACTER_SET_NAME` != 'utf8'
AND `SCHEMA_NAME` != 'mysql'
AND `SCHEMA_NAME` != 'information_schema'");
while($row = $result->fetch_array()) {
$schemaName = $row['SCHEMA_NAME'];
$mysqli->query("ALTER SCHEMA `$schemaName` CHARACTER SET = utf8") or die('Error: '.$mysqli->error);
$mysqli->query("ALTER SCHEMA `$schemaName` COLLATE = utf8_general_ci") or die('Error: '.$mysqli->error);
echo "Converted `$schemaName`\n";
}
?>
To avoid this problem in the future. Create the following files in /etc/mysql/conf.d
(debian specific setup, should work on other distributions as well)
## FILE: character_encoding.cnf
[client]
default-character-set = utf8
[mysqld]
character-set-server = utf8
collation-server = utf8_general_ci
## FILE: default_storage_engine.cnf
[mysqld]
default-storage-engine = innodb
@BrunIF
Copy link

BrunIF commented Jan 6, 2017

Better collation is utf8_unicode_ci. It support cyrillic letters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment