从MySQL中获取中文数据

今天测试了一下从MySQL中获得中文数据,发现需要进行一些处理才能在网页中完美显示中文(在PHPMYADMIN中插入、显示是正常的):

首先,当然是你的MySQL数据库是基于UTF-8建立的。 然后是在PHP中的常规连接:

$hostname_test = localhost;
$database_test = test;
$username_test = root;
$password_test = xxxxxx;
$test = mysql_pconnect($hostname_test, $username_test, $password_test) or trigger_error(mysql_error(),E_USER_ERROR); 
$query=select * from chinese; mysql_select_db($database_test, $test); 
**$xx=set names utf8; mysql_query($xx);**
$rs=mysql_query($query, $test);
while($row=mysql_fetch_object($rs))
{
    echo $row->id.<br/>;
    echo $row->desc.<br/>;
    echo =====================
    <br/>;
}

注意上面的黑体部分,这两行很关键。

再然后是在PHP文件中要指定字符集:

<head> <meta http-equiv=Content-Type content=text/html; charset=utf-8> </head>

注意,这里要写utf-8,而set names时要写utf8。

Comments

One response to “从MySQL中获取中文数据”

  1. […] 这个问题说穿了还是MySQL返回字符串时使用的字符集的问题。这个问题我在之前的文章中已经描述过了,今天的解决方法还是完全一样。短短一个多月,我就忘记了这个问题,真是强烈的874自己。所以再次将这个问题写出来,再次的提醒自己。 […]

Leave a Reply to 生活在远方 » Blog Archive » 八月十七日 Cancel reply

Your email address will not be published. Required fields are marked *