Skip to content

Instantly share code, notes, and snippets.

@AndreasBaumgart
Created June 4, 2010 14:32
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 AndreasBaumgart/425473 to your computer and use it in GitHub Desktop.
Save AndreasBaumgart/425473 to your computer and use it in GitHub Desktop.
Alter the encoding type of all text-like columns in a MySQL database from anything to UTF8 but without touching the bytes itself. Don't ask.
<?php
$sql = '';
$pdo = Propel::getConnection();
$stmt = $pdo->query('SHOW FULL TABLES');
$tables = $stmt->fetchAll(PDO::FETCH_NUM);
foreach($tables as $tbl) {
$tblName = $tbl[0];
if('BASE TABLE' !== $tbl[1]) {
continue;
}
$columns = $pdo->query("DESCRIBE `$tblName`")->fetchAll(PDO::FETCH_ASSOC);
$partBinary = array();
$partUtf8 = array();
foreach($columns as $col) {
$colName = $col['Field'];
$colType = $col['Type'];
if(preg_match('/^(TEXT|VARCHAR|CHAR).*/i', $colType)) {
$partBinary[] = "MODIFY `$colName` $colType CHARACTER SET binary";
$partUtf8[] = "MODIFY `$colName` $colType CHARACTER SET utf8 COLLATE utf8_general_ci";
}
}
if(count($partBinary)) {
$sql .= "ALTER TABLE `$tblName` " .PHP_EOL . "\t" . join(', ' . PHP_EOL . "\t" , $partBinary) . PHP_EOL . ';'. PHP_EOL. PHP_EOL;
$sql .= "ALTER TABLE `$tblName` " .PHP_EOL . "\t" . join(', ' . PHP_EOL . "\t" , $partUtf8) . PHP_EOL . ';'. PHP_EOL. PHP_EOL;
}
}
echo $sql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment