PHP MySQL特殊字符

3

我的表格长这样 -

province_id int(11)                  
province_title char(200) utf8_general_ci 
parent int(8) int(2)

我可以帮忙翻译。这段内容涉及到IT技术,主要是关于从phpMyadmin直接插入数据后,在php页面中检索出现特殊字符问题的解决方法。

例如——

Québec shows -  Qu�bec.

我的HTML标题看起来像这样 -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

我认为问题可能出现在插入数据时。如何在phpMyAdmin中转换这些数据?需要帮助吗?


你真的想使用char(200)吗?数据库管理系统会使用大量填充并浪费磁盘空间。为什么不改用varchar呢?另外,如果你改用varchar,并且要在父列上进行搜索(例如查找子项),你可能希望将其放在varchar之前作为固定宽度,就像int列应该通常放在前面一样(可以加快搜索速度)。 - daiscog
4个回答

4

看起来你没有在所有地方使用utf-8,所以你的数据在某个时候被弄乱了。根据你具体在做什么,你需要改变/添加以下一个或多个点(很可能是你忘记的SET CHARSET/mysql_set_charset):

  • tell MySQL to use utf-8. to do this, add this to your my.cnf:

    collation_server = utf8_unicode_ci
    character_set_server = utf8
    
  • before interacting with mysql, send this two querys:

    SET NAMES 'utf8';
    CHARSET 'utf8';
    

    or, alternatively, let php do this after opening the connection:

    mysql_set_charset('utf8', $conn); // when using the mysql_-functions
    mysqli::set_charset('utf8') // when using mysqli
    
  • set UTF-8 as the default charset for your database

    CREATE DATABASE `my_db` DEFAULT CHARACTER SET 'utf8';
    
  • do the same for tables:

    CREATE TABLE `my_table` (
      -- ...
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
  • assuming the client is a browser, serve your content as utf-8 and the the correct header:

    header('Content-type: text/html; charset=utf-8');
    

    to be really sure the browser understands, add a meta-tag:

    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    
  • and, last but not least, tell the browser to submit forms using utf-8

    <form accept-charset="utf-8" ...>
    

1
+1 给一个非常完整的回答。由于不鼓励使用MySQL,我建议您添加“或使用mysqli :: set_charset”作为替代方案。 - daiscog

0

MySQL服务器默认情况下未配置以UTF-8编码接收客户端数据。

所以你必须使用以下方式打开连接:

mysql_query("SET NAMES utf8");   

如果您正在使用PDO,
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 

$dbh = new PDO($dsn, $username, $password, $options);

0

0
如果在phpmyadmin中查看数据时看起来正常,那么问题可能出在文件本身的文本编码上。
使用Eclipse(编辑»设置编码)或Notepad++(编码)确认文件中是否有正确的编码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接