Immer wieder muss ich alte Seiten in auf UTF-8 umzustellen. Ganz wichtig dabei, die Datenbank. Mit folgendem Script habe ich diverse Seiten bereits erfolgreich umgestellt.
<a href="http://www.php.net/define">define</a>('DB_HOST', 'localhost'); <a href="http://www.php.net/define">define</a>('DB_NAME', 'datenbank_name'); <a href="http://www.php.net/define">define</a>('DB_USER', 'benutzer'); <a href="http://www.php.net/define">define</a>('DB_PASSWD', 'passwort'); <a href="http://www.php.net/mysql_connect">mysql_connect</a>(DB_HOST, DB_USER, DB_PASSWD); <a href="http://www.php.net/mysql_select_db">mysql_select_db</a>(DB_NAME); $result = <a href="http://www.php.net/mysql_query">mysql_query</a>("SHOW TABLES"); while($row = <a href="http://www.php.net/mysql_fetch_assoc">mysql_fetch_assoc</a>($result)) { $tableName = $row['Tables_in_'.DB_NAME]; $fields = <a href="http://www.php.net/array">array</a>(); $primaryKey = null; <a href="http://www.php.net/mysql_query">mysql_query</a>("ALTER TABLE `{$tableName}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci"); $_result = <a href="http://www.php.net/mysql_query">mysql_query</a>("DESCRIBE `{$tableName}`"); while($_row = <a href="http://www.php.net/mysql_fetch_assoc">mysql_fetch_assoc</a>($_result)) { if(<a href="http://www.php.net/isset">isset</a>($_row['Key']) && $_row['Key'] == 'PRI' && !$primaryKey) { $primaryKey = $_row['Field']; } if(<a href="http://www.php.net/strpos">strpos</a>($_row['Type'], 'varchar') !== false || <a href="http://www.php.net/strpos">strpos</a>($_row['Type'], 'text') !== false) { $fields[] = $_row['Field']; <a href="http://www.php.net/mysql_query">mysql_query</a>("ALTER TABLE `{$tableName}` CHANGE `{$_row['Field']}` `{$_row['Field']}` {$_row['Type']} CHARACTER SET utf8 COLLATE utf8_general_ci"); } } if(!<a href="http://www.php.net/empty">empty</a>($fields) && !<a href="http://www.php.net/empty">empty</a>($primaryKey)) { $fields[] = $primaryKey; $_result = <a href="http://www.php.net/mysql_query">mysql_query</a>("SELECT `".<a href="http://www.php.net/implode">implode</a>('`,`', $fields)."` FROM `{$tableName}`"); while($_row = <a href="http://www.php.net/mysql_fetch_assoc">mysql_fetch_assoc</a>($_result)) { $values = <a href="http://www.php.net/array">array</a>(); foreach($_row as $field => &$value) { if($field != $primaryKey && !<a href="http://www.php.net/empty">empty</a>($value)) { $values[] = "`".$field."` = '".<a href="http://www.php.net/utf8_encode">utf8_encode</a>($value)."'"; } } $sql = "UPDATE `{$tableName}` SET ".<a href="http://www.php.net/implode">implode</a>(',', $values)." WHERE `{$primaryKey}` = '{$_row[$primaryKey]}'"; <a href="http://www.php.net/mysql_query">mysql_query</a>($sql); } } } |