UTF-8 MySQL和字符集 [英] UTF-8 MySQL and Charset

查看:84
本文介绍了UTF-8 MySQL和字符集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将所有内容都设置为UTF-8时,有人可以向我解释我吗?

Can someone explain me when I set everything to UTF-8 I keep getting those damn ���

MySQL
伺服器版本:5.1.44
MySQL字符集:UTF-8 Unicode(utf8)

MySQL
Server version: 5.1.44
MySQL charset: UTF-8 Unicode (utf8)

我创建一个新数据库

名称:utf8test
排序规则:utf8_general_ci
MySQL连接排序规则:utf8_general_ci

name: utf8test
collation: utf8_general_ci
MySQL connection collation: utf8_general_ci

我的SQL看起来像这样:

My SQL looks like this:

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

CREATE TABLE IF NOT EXISTS `test_table` (
    `test_id` int(11) NOT NULL,
    `test_text` text NOT NULL,
    PRIMARY KEY (`test_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `test_table` (`test_id`, `test_text`) VALUES
(1, 'hééélo'),
(2, 'wööörld');

我的PHP/HTML:

My PHP / HTML:

<?php
$db_conn = mysql_connect("localhost", "root", "") or die("Can't connect to db");
mysql_select_db("utf8test", $db_conn)  or die("Can't select db");

// $result = mysql_query("set names 'utf8'"); // this works... why??
$query = "SELECT * FROM test_table";        
$result = mysql_query($query);

$output = "";
while($row = mysql_fetch_assoc($result)) {
    $output .= "id: " . $row['test_id'] . " - text: " . $row['test_text'] . "<br />";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="it" xmlns="http://www.w3.org/1999/xhtml" xml:lang="it">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>UTF-8 test</title>
</head>
<body>
<?php echo $output; ?>
</body>
</html>

推荐答案

我将所有内容都设置为UTF-8

I set everything to UTF-8

不完全是.
您必须告诉mysql您的 client 的编码.

Not quite.
You have to tell mysql your client's encoding.

事实上,您不必在utf-8中设置所有内容".您可以将表放在latin1中,并在utf-8中输出.或相反.
非常灵活.

As a matter of fact, you don't have to set up "everything" in utf-8. You can have your tables in latin1 and output in utf-8. Or contrary.
Very flexible.

但是您必须显式设置客户端的编码. 因此,这就是为什么它可以与set names utf8一起使用的原因.因为此查询设置了客户端的编码.并让Mysql知道必须在utf-8中发送数据.很明智,是吧?

But you have to set up client's encoding explicitly. So, that's why it works with set names utf8. Because this query setting up client's encoding. And let Mysql know that data must be sent in utf-8. Pretty sensible, huh?

我还要提到您的SQL转储.它需要相同的设置.只需在顶部某处设置名称即可.因为您也是从某些客户端发送这些查询.并且还需要设置此客户端的编码.

Also I have to mention your SQL dump. It needs same setting. Just SET NAMES somewhere at the top. Because you are sending these queries from some client too. And this client's encoding needs to be set up as well.

还有一件事要提:确保您的服务器在Content-type标头中发送正确的编码.您也没有将其设置为UTF-8.

And one more thing to mention: be sure your server sending proper encoding in the Content-type header. You didn't set it to UTF-8 too.

这篇关于UTF-8 MySQL和字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆