2012-03-25 24 views
3

我將所有mysql錶轉換爲utf-8_unicode並開始使用mysql_set_charset('utf8');函數。使用mysql_set_charset('utf8')函數替換UTF-8字符

但在此之後,最喜歡S的某些字符,Ö開始尋找像A-,AZ

我怎麼能替換使用UTF-8格式的mysql這有點信嗎?

不久,我可以找到所有這些有點字符替換的列表嗎?

編輯: 他在這篇文章中解釋過這個問題,但實際上我不明白它正確地實際上可以笑

http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html

回答

10
你不

需要做的。數據庫連接後使用此代碼。

mysql_query("SET NAMES 'utf8'"); 
mysql_query("SET CHARACTER SET utf8"); 
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'"); 

並在所有頁面中使用utf-8字符集。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
+0

檢查此頁面,有人建議我使用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

+1

我使用這個,它的完美工作正常。和我使用兩個,設置名稱和設置字符集像他說的。 – guybennet 2012-03-25 22:49:30

+0

其實問題不在於打印文本,問題是關於mysql中存儲的文本。我必須替換它們。 – 2012-03-25 22:51:12

4

這個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