Home >php教程 >php手册 >解决php插入数据到mysql中文乱码问题

解决php插入数据到mysql中文乱码问题

WBOY
WBOYOriginal
2016-05-27 08:47:401470browse

php+mysql数据时我们必须保证提交到数据库的编码与mysql编码是一致的这样才可以保存中文不出现问号乱码问题,下面我先整理两个让mysql与页面保证编码一致的方法.

解决中文插入数据库乱码的方法,直接把中文转变成utf-8格式,大多是这个问题导致的,代码如下:

$str = iconv('gbk','utf-8',$str);

如果还不行检查网页编码是否正确,代码如下:

<?php header("Content-Type:text/html;charset=utf-8");?>

例子,由于我懒得写,网上的这个例子感觉还挺清楚的,建表,代码如下:

Create TABLE `net_city` ( 
`cityid` smallint(4) NOT NULL auto_increment, 
`cityname` varchar(80) NOT NULL default &#39;&#39;, 
`provinceid` smallint(2) NOT NULL default &#39;0&#39;, 
`inarea` varchar(5000) NOT NULL default &#39;&#39;, 
`outarea` varchar(5000) NOT NULL default &#39;&#39;, 
`tel` varchar(400) NOT NULL default &#39;&#39;, 
PRIMARY KEY (`cityid`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

PHP里的代码:

$conn=mysql_connect("localhost", "用户名", "密码"); 
 
mysql_query("set names &#39;utf8&#39;",$conn); 
mysql_select_db(" www.phprm.com 数据名",$conn); 
$exec="insert into net_city (cityname,inarea,outarea,tel) values (&#39;".$link_cityname."&#39;,&#39;".$link_inarea."&#39;,&#39;".$link_outarea."&#39;,&#39;".$link_tel."&#39;)"; 
$result=mysql_query($exec,$conn); 
if($result){ 
   echo "1"; 
 }else{ 
echo "0"; 
 } 
mysql_close($conn);

后来我试了试全部都用成gbk的,也是可以的,在查询数据时我们直接使用mysql_query()来设置:mysql_query("SET NAMES GBK");  //GBK处为编码设置

例子,下面是 "insert.php" 页面的代码:

<?php
$con = mysql_connect("localhost","peter","abc123"); 
if (!$con) { die(&#39;Could not connect: &#39; . mysql_error()); } 
mysql_select_db("my_db", $con); 
mysql_query("SET NAMES GBK");  //GBK处为编码设置 
$sql="INSERT INTO person (FirstName, LastName, Age)VALUES(&#39;$_POST[firstname]&#39;,&#39;$_POST[lastname]&#39;,&#39;$_POST[age]&#39;)"; 
if (!mysql_query($sql,$con)) 
{ die(&#39;Error: &#39; . mysql_error()); } 
echo "1 record added"; 
mysql_close($con)

   


教程链接:

随意转载~但请保留教程地址★

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn