Skip to content

Instantly share code, notes, and snippets.

@tskrynnyk
Created April 19, 2012 11:04
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 tskrynnyk/2420258 to your computer and use it in GitHub Desktop.
Save tskrynnyk/2420258 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("ALTER TABLE $table MODIFY $column $type CHARACTER SET $new_charset COLLATE $new_collation");
}
print "changed collation of $table to $new_collation<br/>";
}
print '<br/>The collation of your database has been successfully changed!<br/>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment