Skip to content

Instantly share code, notes, and snippets.

@perifer
Created December 20, 2010 15:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perifer/748509 to your computer and use it in GitHub Desktop.
Save perifer/748509 to your computer and use it in GitHub Desktop.
Script for change the collation of a database's table (utf8)
#!/usr/bin/env php
<?php
/**
* Script for change the collation of a database's table's
*/
if ($argv[1] == '-h') {
echo "Usage:\n\tphp collation_switch.php sql-user sql-password sql-database target-collation target-character\nExample: php collation_switch.php USER PASS DATABASE utf8_swedish_ci utf8\n";
die();
}
$start = microtime(TRUE);
$errors = 0;
$sql = new MySQLi('127.0.0.1', $argv[1], $argv[2], $argv[3]);
if (mysqli_connect_error()) {
die("Failed to connect to database. MySQL said:\n\t" . mysqli_connect_error());
}
echo "-----------------------------\n";
echo "Altering database: {$argv[3]}\n";
$result = $sql->query("ALTER DATABASE `" . $argv[3] . "` COLLATE=" . $argv[4]);
if ($result) {
echo "SUCCESS!\n";
} else {
echo "ERROR\n";
$errors++;
}
$tables = $sql->query('SHOW TABLES');
if ($tables) {
while ($table = $tables->fetch_array()) {
$t = $table[0];
echo "-----------------------------\n";
echo "Altering table: {$t}\n";
$result = $sql->query("ALTER TABLE $t CONVERT TO CHARACTER SET $argv[5] COLLATE $argv[4]");
if ($result) {
echo "SUCCESS!\n";
} else {
echo "ERROR\n";
$errors++;
}
}
} else {
die('Failed to fetch tables for database: ' . $argv[3]);
}
echo "-----------------------------\n";
echo "Completed script in: " . round(microtime(TRUE) - $start, 4) . " seconds.\n";
echo "With " . $errors . " errors.\n\n";
$sql->close();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment