search
HomeBackend DevelopmentPHP Tutorialphp和mysql中uft-8中文编码乱码的几种解决办法

对于乱码这个问题php开发者几乎都会有碰到过,我们下面主要是介绍了php文件乱码和页面乱码以及php mysql数据库连接时乱码解决方法

PHP页面转UTF-8编码问题

1.在代码开始出加入一行:

代码如下:

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

2.PHP文件编码问题

点击编辑器的菜单:“文件”->“另存为”,可以看到当前文件的编码,确保文件编码为:UTF-8,
如果是ANSI,需要将编码改成:UTF-8。

3.PHP文件头BOM问题:

PHP文件一定不可以有BOM标签
否则,会出现session不能使用的情况,并有类似的提示:
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent
这是因为,在执行session_start() 的时候,整个页面不能有输出,但是当由于前PHP页面存在BOM标签,
PHP把这个BOM标签当成是输出了,所以就出错了!
所以PHP页面一定要删除BOM标签

删除这个BOM标签的方法:

1.可以用Dreamweaver打开文件,并重新保存,即可以去除BOM标签!
2.可以用EditPlus打开文件,并在菜单“首选项”->“文件”->"UTF-8标识",设置为:“总是删除签名”,
然后保存文件,即可以去除BOM标签!
4.PHP以附件形式保存文件的时候,UTF-8编码问题:
PHP以附件形式保存文件,文件名必须是GB2312编码,
否则,如果文件名中有中文的话,将是显示乱码:
如果你的PHP本身是UTF-8编码格式的文件,
需要将文件名变量由UTF-8转成GB2312:
iconv("UTF-8", "GB2312", "$filename");
利用程序来实例字符截取方法

代码如下:

function utf8_substr($str,$len) 
{ 
  for($i=0;$i<$len;$i++) 
  { 
    $temp_str=substr($str,0,1); 
    if(ord($temp_str) > 127){ 
      $i++; 
    if($i<$len){ 
      $new_str[]=substr($str,0,3); 
      $str=substr($str,3); 
      } 
    }else { 
    $new_str[]=substr($str,0,1); 
    $str=substr($str,1); 
    } 
  } 
  return join($new_str); 
}

MYSQL数据库使用UTF-8编码的问题

1、用phpmyadmin创建数据库和数据表

创建数据库的时候,请将“整理”设置为:“utf8_general_ci”
或执行语句:

代码如下:

CREATE DATABASE `dbname` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

创建数据表的时候:如果是该字段是存放中文的话,则需要将“整理”设置为:“utf8_general_ci”,
如果该字段是存放英文或数字的话,默认就可以了。
相应的SQL语句,例如:

代码如下:

CREATE TABLE `test` ( 
`id` INT NOT NULL , 
`name` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , 
PRIMARY KEY ( `id` ) 
) ENGINE = MYISAM ;

2.用PHP读写数据库

在连接数据库之后:

代码如下:

$connection = mysql_connect($host_name, $host_user, $host_pass);

加入两行:

代码如下:

mysql_query("set character set &#39;utf8&#39;");//读库 
mysql_query("set names &#39;utf8&#39;");//写库

就可以正常的读写MYSQL数据库了。

用的appserv-win32-2.5.10做的环境,装这个包的时候用默认的utf8编码。
在写数据库连接文件时,写成:

代码如下:

$conn = mysql_connect("$host","$user","$password"); 
mysql_query("SET NAMES &#39;UTF8&#39;"); 
mysql_select_db("$database",$conn);

然后在做页面时,注意这句:

代码如下:

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

这样不管输入数据库的中文,还是页面显示,就都正常了。
在DW CS4版里,默认生成的也是utf8页面。
同样的,如果一开始写数据库连接文件时写成:

代码如下:

mysql_query("SET NAMES &#39;GBK&#39;");

那页面也要相应变成:

代码如下:

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

总结,最后主要是页面编码要统一就可以很方便的解决乱码问题,特别是在mysql_query()这个set names的设置必须和页面及数据库编码统计一就可以了。

更多相关教程请访问 php编程从入门到精通全套视频教程

Statement
This article is reproduced at:脚本之家. If there is any infringement, please contact admin@php.cn delete
Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor