3 月 022014
 

问题 php connect 老是中文乱码 各种都改了 还是不行。

header(“content-Type: text/html; charset=UTF-8”);
define (‘HOSTNAME’, ‘localhost’); //数据库主机名
define (‘USERNAME’, ‘Syslog’); //数据库用户名
define (‘PASSWORD’, ‘Syslog123’); //数据库用户登录密码
define (‘DATABASE_NAME’, ‘Syslog’); //需要查询的数据库
$db = mysql_connect(HOSTNAME, USERNAME, PASSWORD) or
die (mysql_error());
//连接不上,就会显示mysql出错的原因。
mysql_select_db(DATABASE_NAME);
//切换到testdb
//mysql_query(“set names utf8;”);
//mysql_query(“set names ISO-8859-15;”);
//mysql_query(“SET NAMES ‘UTF8′”);
//mysql_query(“SET CHARACTER SET UTF8”);
//mysql_query(“SET CHARACTER_SET_RESULTS=UTF8′”);
$query =”select Message from SystemEvents where SysLogTag like ‘test121%'”;
//上面这句的意思是从testdb中随机提取一条数据。
$result = mysql_query($query);
//查询
while ($row = mysql_fetch_array($result))
{ echo ”

” .($row[‘Message’]) . “

“; }
//显示结果
mysql_free_result($result);
//释放结果
mysql_close();
//关闭连接
?>

加上mysql_query(“set names utf8;”); 即可 ,但是这要修改代码,还可以更改服务器配置即可。

前面说到的方法是以前用到的常用方法,最近在MySQL的官方发现了这样一个参数 initconnect ,它的意思呢就是在MySQL启动的时候,自动执行initconnect 参数里面的SQL语句,支持用分号间隔的多个语句,于是我们可以把 SET NAMES utf8语句加到my.ini文件里面,在PHP程序里面就不用单独处理了,
加入参数的方法很简单,就是在my.ini文件的 [mysqld] 段加入下面一行 init_connect=’SET NAMES utf8′
不过这个方法有一个需要注意的地方,那就是该参数对于连接数据库的用户是超级用户组的用户将被忽略,那么在PHP程序中用来连接MySQL数据库的用户不能是SUPER组的用户,比如root用户就肯定不行,这样是为了避免该参数导致数据库致命错误,而无法使用任何一个用户连接上修改该项配置,之前我搞了两天都没有发现这样的问题,害我郁闷了很久。。。

 Posted by at 上午 6:25

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny