Skip to content

Instantly share code, notes, and snippets.

@emamut
Forked from tskrynnyk/change-the-collation.php
Last active October 13, 2016 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emamut/be935dfbe7f0b3b0b908ec0b43aa5b4b to your computer and use it in GitHub Desktop.
Save emamut/be935dfbe7f0b3b0b908ec0b43aa5b4b to your computer and use it in GitHub Desktop.
Changing the collation of all tables in a mysql database.
<?php
// Stolen from: http://www.holisticsystems.co.uk/blog/?p=931
$server = 'localhost';
$username = 'user';
$password = 'password';
$database = 'database';
$new_charset = 'utf8';
$new_collation = 'utf8_general_ci';
// Connect to database
$db = mysql_connect($server, $username, $password); if(!$db) die("Cannot connect to database server -".mysql_error());
$select_db = mysql_select_db($database); if (!$select_db) die("could not select $database: ".mysql_error());
// Change database collation
mysql_query("ALTER DATABASE $database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
// Loop through all tables changing collation
$result=mysql_query('show tables');
while($tables = mysql_fetch_array($result)) {
$table = $tables[0];
mysql_query("ALTER TABLE $table DEFAULT CHARACTER SET $new_charset COLLATE $new_collation");
// Loop through each column changing collation
$columns = mysql_query("SHOW FULL COLUMNS FROM $table where collation is not null");
while($cols = mysql_fetch_array($columns)) {
$column = $cols[0];
$type = $cols[1];
mysql_query("SET FOREIGN_KEY_CHECKS=0;");
mysql_query("ALTER TABLE $table MODIFY $column $type CHARACTER SET $new_charset COLLATE $new_collation");
mysql_query("SET FOREIGN_KEY_CHECKS=1;");
}
print "changed collation of $table to $new_collation\n";
}
print "\n\nThe collation of your database has been successfully changed!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment