网站开通天天学习频道
发新话题
打印

[PHP] 解决php读取数据库乱码

解决php读取数据库乱码

以数据库mysqlcode为例

实例代码:
<?php
$conn = mysql_connect("localhost","root","");
mysql_query("set names 'gbk'");//这就是指定数据库字符集,一般放在连接数据库后面就系了
mysql_select_db("test");

$sql = "select * from mysqlcode";
$result = mysql_query($sql,$conn);

?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>mysql 字符编码</title>
</head>

<body>
<table width="300" height="32" border="1" align="center" cellpadding="0" cellspacing="0">
   <tr>
     <td width="71" align="center">id</td>
     <td width="229" align="center">内容</td>
   </tr>
<?php while($row = mysql_fetch_assoc($result)){
echo "  
<tr>
     <td align=\"center\">".$row['id']."</td>
     <td>".$row['content']."</td>
   </tr>";
}?>  
</table>
</body>
</html>
<?php mysql_free_result($result);?>

如果我们将mysql_query("set names 'gbk'");注释掉,肯定时乱码
加上那句又正常了


注意: set names 必须在连接数据库之后,执行sql语句之前!
一句话
你数据库用什么编码,在对数据库操作之前就set names '你的编码';

ps:页面申明编码:在HTML代码HEAD里面,可以用<meta http-equiv="Content-Type" content="text/html; charset="XXX" />来告诉浏览器网页采用了什么编码,目前中文网站开发中主要用的是GB2312和UTF-8两种编码。
大学生计算机交流社区
http://www.stupc.org/

solotraveler,来自SPARK星球的冰冷之火
感谢大家对社区的支持
http://www.stupc.org

TOP

发新话题