PHP调用mysql数据库小语种或中文出现乱码

数据库乱码,编程转码问题都让人头疼。做小语种网站容易出现这些问题,首先你要确定你PHP文件的编码为UTF-8,头部声明也要UTF-8,另外就是在mysql_connect后面加一句SET NAMES UTF8,即可使得UTF8的数据库消除乱码,对于GBK的数据库则使用SET NAMES GBK,代码如下:

$abc = mysql_connect($mysql_host, $mysql_user, $mysql_pass);
mysql_query("SET NAMES 'GBK'");
mysql_query("SET NAMES 'UTF8'");
如果是:new mysqli 可以试试:mysqli_query($db, "set names UTF8");
数据库常用编码类型:utf8_general_ci;

另附一段不报警警告的连接方法:

<?php
$con = mysql_connect('$mysql_host', '$mysql_user', '$mysql_pass');
mysql_query("SET NAMES 'UTF8'");
if (!$con) { die('Could not connect: ' . mysql_error()); }
$db_selected = mysql_select_db("dbname", $con);
$sql = "select * from wp_posts where post_status='publish' order by ID DESC limit 0,4";
$result = mysql_query($sql, $con);
while($row = mysql_fetch_object($result)){
$title=$row->post_title;
$postname=substr($title, 0, 80);
$url= $row->post_name;
echo "<li><a href='http://www.xxx/".$url."'>".$postname."</a></li>";
}
mysql_free_result($result);
mysql_close();
?>

PHP连接ACCESS, sqlite 等数据库乱码问题:

access内部都是unicode存储的,读取的时候指定编码读取就可以了!如像上面的mysql是mysql_query(“set names ‘UTF8′”); access是65001;
但要注意一点php.ini开启extension=php_com_dotnet.dll,没有在后面加上一句这个就行了。
下面是个例子:

 <?php
$rs =new COM("ADODB.RecordSet");
$dbc = new COM("ADODB.Connection",NULL,65001) or die("ADO connect failed!");
$connstr="DRIVER=Microsoft Access Driver (*.mdb);DBQ=c:\date.mdb";
$dbc->open($connstr);
$rs=$dbc->execute("select * from a");
$i=0;
while (!$rs->eof){
$i+=1;
$fld0=$rs->fields["title"];
echo "$fld0->value";
$rs->movenext();
}
$rs->close();
?>

发表评论