插入数据库后,Unicode字符成为问号

时间:2010-07-31 11:51:06

标签: php mysql unicode utf-8

当我将一些用Unicode编写的文本插入数据库时​​,它们就成了问号。数据库编码设置为UTF-8。还有什么可能不正确?当我签入phpMyAdmin时,只插入了问号!

这是我用来连接数据库的代码:

define ("DB_HOST", "localhost"); // Set database host
define ("DB_USER", "root"); // Set database user
define ("DB_PASS","password"); // Set database password
define ("DB_NAME","name"); // Set database name

$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");

mysql_set_charset('utf8',$link);
mysql_query("SET CHARACTER SET utf8");

4 个答案:

答案 0 :(得分:4)

您插入的文字是否也以UTF-8编码?或者你的PHP文件不是UTF-8?您是否已将MySQL客户端连接设置为UTF-8?

如果没有,那么这可能是问题的原因。

答案 1 :(得分:2)

你怎么知道问号?您是否在PHP页面上,输出数据库字段或phpMyAdmin等软件中将它们视为问号?

无论哪种方式,问题可能是您的网页而不是数据库的编码。请务必添加以下行:

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

答案 2 :(得分:1)

 // First make sure your file produce UTF-8 characters
 header('Content-Type: text/html; charset=utf-8');
 // Make sure with your spelling
 // write
 mysql_query("SET CHARSET utf8");
 // Instead of
 mysql_query("SET CHARACTER SET utf8");

 // For some reasons
 mysql_query("SET CHARSET SET utf8");
 // It works on some servers and for other servers not. I am not sure why.

 // Try using mysql_set_charset("utf8"); only without mysql_query("SET CHARSET utf8");
 // For me I had the same issue with my server
 // When I used mysql_set_charset("utf8"); only --> the problem solved
 // again make sure with your spelling and try again

答案 3 :(得分:-1)

抱歉,但你错了......

我的朋友King Julien,你必须执行:

mysql_query("SET CHARACTER SET utf8");
mysql_query("SET CHARSET utf8");
mysql_query("SET COLLATION_CONNECTION = 'utf8_unicode_ci'"); // This statement does the job!!! ;)

度过美好的一天!