這個PHP腳本允許您將現有的數據庫和錶轉換爲UTF-8:
<?php
// Database connection details
$db_srv = 'localhost';
$db_usr = 'user';
$db_pwd = 'password';
$db_name = 'database name';
// New charset information, update accordingly if not UTF8
$char_set = 'utf8';
$char_collation = 'utf8_general_ci';
header('Content-type: text/plain');
// extablish the connection
$connection = mysql_connect($db_srv,$db_usr,$db_pwd) or die(mysql_error());
// select the databse
$db = mysql_select_db($db_name) or die(mysql_error());
// get existent tables
$sql = 'SHOW TABLES';
$res = mysql_query($sql) or die(mysql_error());
// for each table found
while ($row = mysql_fetch_row($res))
{
// change the table charset
$table = mysql_real_escape_string($row[0]);
$sql = " ALTER TABLE ".$table."
DEFAULT CHARACTER SET ".$char_set."
COLLATE ".$char_collation;
mysql_query($sql) or die(mysql_error());
echo 'The '.$table.' table was updated successfully to: '.$char_set."\n";
}
// Update the Collation of the database itself
$sql = "ALTER DATABASE CHARACTER SET ".$char_set.";";
mysql_query($sql) or die(mysql_error());
echo 'The '.$db_name.' database collation';
echo ' has been updated successfully to: '.$char_set."\n";
// close the connection to the database
mysql_close($connection);
?>
將它保存在一個文件中,可以說db_charset.php
,把它上傳到你的網站的根從瀏覽器中執行:
例如,
http://www.yoursite.com/db_charset.php
其他的考慮是必要的,擁有一切在轉換後正常工作:
- 使用應使用UTF-8
- 的PHP頭和HTML頭也應被設置爲編碼的PHP文件UTF-8
檢查此頁面,有人建議我使用mysql_set_charset而不是設置名稱,因爲我之前使用它http://stackoverflow.com/questions/9703536/bad-characters-when-printing-text- from-utf8-unicode-ci-mysql-table – 2012-03-25 22:45:42
我使用這個,它的完美工作正常。和我使用兩個,設置名稱和設置字符集像他說的。 – guybennet 2012-03-25 22:49:30
其實問題不在於打印文本,問題是關於mysql中存儲的文本。我必須替換它們。 – 2012-03-25 22:51:12