使用mysql_set_charset('utf8')函数后,用UTF-8替换字符

时间:2012-03-25 22:36:03

标签: php utf-8

我将所有mysql表转换为utf-8_unicode并开始使用mysql_set_charset('utf8');函数。

但在此之后,像Ş,Ö这样的角色开始看起来像Ã,Åž

如何用UTF-8格式替换mysql中的这种字母?

很快,我能找到要替换的所有这些角色的列表吗?

编辑: 他实际上在这篇文章中解释了这个问题,但是我无法理解它的实际情况lol

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

2 个答案:

答案 0 :(得分: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" />

答案 1 :(得分: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

在转换后让一切正常工作需要其他注意事项:

  • 正在使用的PHP文件应使用UTF-8
  • 进行编码
  • PHP标头和HTML标头也应设置为UTF-8