dongsuo0517
2013-04-22 15:37
浏览 103
已采纳

UTF-8给了我问号

I have this simple PHP-script, which searches a mySQL database and outputs the result to the user. I used to use ISO-8859-1 as my charset, but was advised to use UTF-8. But I have trouble going from my former charset to the new one.

To clarify some things, I have:

  • Created a database and table encoded in UTF-8 with collation utf8_unicode_ci.
  • Encoded my PHP-file in UTF-8.
  • Set meta charset to UTF-8.
  • Set all text mime-types to UTF-8 through create-mime.assign.pl in Lighty (Lighttpd).

Now, the problem arises when I retrieve data from the database with characters like ö, ü etc. If I just do echo "ö"; without retrieving it from the database, it works fine. I guess there must be something wrong with the database then?

I've tried the following, and they've solved my problem:

  • Set meta charset to ISO-8859-1 (which, for some strange reason works, but breaks the echo'd "ö").
  • Set a utf8_decode() function around the output.
  • After mysql_select_db() declared the following mysql_set_charset('utf8');.

I know that I've found multiple solutions, but I just don't know why it wont work without them? And is it bad practice to use utf8_decode() on output, or the mysql_set_charset() function?

图片转代码服务由CSDN问答提供 功能建议

我有这个简单的PHP脚本,它搜索mySQL数据库并将结果输出给用户。 我以前使用 ISO-8859-1 作为我的字符集,但建议使用 UTF-8 。 但是我很难从我以前的字符集转到新的字符集。

为了澄清一些事情,我有:

  • 创建 以 UTF-8 编码的数据库和表,其中包含collat​​ion utf8_unicode_ci
  • UTF-8中编码我的PHP文件
  • 将元字符集设置为 UTF-8
  • 将所有文本 mime-types 设置为 Lighty(Lighttpd)中的 UTF-8 create-mime.assign.pl

    现在, 当我使用öü等字符从数据库中检索数据时出现问题。如果我只是执行 echo“ö”; 而不检索 它来自数据库,它工作正常。 我猜数据库肯定有问题吗?

    我尝试了以下内容,他们已经解决了我的问题:

      \ n
    • 将元字符集设置为 ISO-8859-1 (由于某些奇怪的原因,它会起作用,但会打破echo“ö”)。
    • 设置 输出周围的 utf8_decode()函数。
    • mysql_select_db()之后声明了以下 mysql_set_charset('utf8'); < /code>.
    nn

    我知道我找到了多种解决方案,但我不知道为什么没有它们就无法工作? 在输出上使用 utf8_decode() mysql_set_charset()函数是不好的做法?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongwende1984 2013-04-22 15:43
    已采纳

    MySQL is funny with UTF8. You need to ensure the server is running in UTF and that the connection is as well

    If you can modify the my.cnf file on your server you can add these to the [mysqld] section and restart it

    character-set-server = utf8
    skip-character-set-client-handshake
    

    You could alternatively (or as well) use

    query("SET NAMES utf8");   
    

    before sending/retrieving data to ensure the database expects UTF8 data to be passed

    点赞 打赏 评论

相关推荐 更多相似问题