Skip to content

Instantly share code, notes, and snippets.

@neotohin
Created April 5, 2023 11:03
Show Gist options
  • Save neotohin/95e309e731b6c4243f3a2c5e27833d50 to your computer and use it in GitHub Desktop.
Save neotohin/95e309e731b6c4243f3a2c5e27833d50 to your computer and use it in GitHub Desktop.
MySQL Collate fix
<?php
// Stolen from: http://www.holisticsystems.co.uk/blog/?p=931
// Modified to work using mysqli
$server = 'localhost';
$username = 'root';
$password = 'root';
$database = 'ojs';
$new_charset = 'utf8';
$new_collation = 'utf8_unicode_ci';
// Connect to database
$db = mysqli_connect($server, $username, $password); if(!$db) die("Cannot connect to database server -".mysqli_error());
$select_db = mysqli_select_db($db, $database); if (!$select_db) die("could not select $database: ". mysqli_error());
// Change database collation
mysqli_query($db, "ALTER DATABASE $database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
// Loop through all tables changing collation
$result=mysqli_query($db, 'show tables');
while($tables = mysqli_fetch_array($result)) {
$table = $tables[0];
mysqli_query($db, "ALTER TABLE $table DEFAULT CHARACTER SET $new_charset COLLATE $new_collation");
// Loop through each column changing collation
$columns = mysqli_query($db, "SHOW FULL COLUMNS FROM $table where collation is not null");
while($cols = mysqli_fetch_array($columns)) {
$column = $cols[0];
$type = $cols[1];
mysqli_query($db, "SET FOREIGN_KEY_CHECKS=0;");
mysqli_query($db, "ALTER TABLE $table MODIFY $column $type CHARACTER SET $new_charset COLLATE $new_collation");
mysqli_query($db, "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