Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial mysql插入中文乱码

mysql插入中文乱码

Jun 23, 2016 pm 02:20 PM

php文件里设置了网页编码为utf-8
header("Content-type:text/html; charset=utf-8"); 

插入数据库前设置了传递给数据库的编码为utf-8
$this->mysqli->query("set names utf8");

数据库中,设置了一些字符集有关的变量
查询show variables like 'char%';后结果为


查询show variables like 'collation_%';后结果为


我用的WampServer,修改mysql配置文件my.ini,在[client]节点下添加default-character-set=utf8 ,在[mysqld]节点下添加character_set_server=utf8,然后重启musql服务


但是传到数据库里,中文字符都变成了问号。。请问应该如何设置才能解决乱码?


回复讨论(解决方案)

把你做的所有修改都还原的初始状态!

需要注意的是:
1、所有与字符集相关的设置,都不会影响到数据库中的已有数据
2、字符集相关的设置,只对设置后插入的数据生效
3、数据库是共有资源,不要轻易修改设置。以免引发其他应用的问题

只要做到以下两点,就不会出现乱码问题
1、所有可能会有中文内容的字段,都需要有中文字符集的连接校对。至于是哪个字符集都无所谓(gbk、utf8、ucs2都可以)也不需要每个字段都相同
2、每次在连接数据库之后,执行一次 set name 页面字符集

我就是设置完数据库字符集后删除数据表中原有乱码数据,再执行程序,插入的中文还是乱码。

因为自己练习用的是测试数据库,所以就修改了字符集设置。我自己也记不清默认配置是什么了,怎么恢复啊。。。

每次连接数据库后,我都执行$this->mysqli->query("set names utf8"); 应该没有问题吧?
所有可能会有中文内容的字段,都需要有中文字符集的连接校对,这个每太明白,是指show variables like 'collation_%';语句执行后显示的结果吗?

新手刚入门,请大神不吝赐教,感谢不尽。

连接数据库的工具类

<?php  class MysqliHelper{    private $mysqli;	private static $host = "localhost";    private static $user = "root";	private static $pwd = "";	private static $db = "test";		public function __construct(){	  $this->mysqli = new Mysqli(self::$host,self::$user,self::$pwd,self::$db);	  if($this->mysqli->connect_error){	     die("连接数据库失败".$this->mysqli->connect_error);	  }	   $this->mysqli->query("set names utf8");	}		public function execute_dql($sql){	    $res = $this->mysqli->query($sql) or die($this->mysqli->error);	    return $res;	}		public function execute_dml($sql){	     $res = $this->mysqli->query($sql) or die($this->mysqli->error);		 		 if(!$res){		    return 0;		 }else{		    if($this->mysqli->affected_rows>0){			  return 1;			}else{			  return 2;			}		 }	}  }?>
Copy after login


表的字符集是什么?应该不影响你的保存结果~

表的字符集是什么?应该不影响你的保存结果~

怎么查看表的字符集?我用的都是默认的字符集,修改过的配置请看一楼截图。

shou create table 表名; 或者用phpmyadmin图形化工具也可以查看。

打错,是 show create table 表名; 

CREATE TABLE `tb_userinfo` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=latin1



是latin1啊,怎么改成utf8?

CREATE TABLE `tb_userinfo` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=latin1



是latin1啊,怎么改成utf8?

进入phpmyadmin修改

删去原表
drop table tb_userinfo

重新创建
CREATE TABLE `tb_userinfo` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8

其实可以不用这么做
只需修改连接校对就可以了
ALTER TABLE `tb_userinfo` CHANGE `username` `username` VARCHAR( 20 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL 

改了表字符集,字段也是要改的,你就drop table; 后再重新建表。

CREATE TABLE `tb_userinfo` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  `email` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=90 DEFAULT CHARSET=utf8;

注意备份数据就好了。其实如果你不担心用phpmyadmin查看乱码的话,只要在php链接数据库的时候设置好字符集,不影响数据的存取。。。正常的话,网站下尽量不挂phpmyadmin,随用随传,免得出问题~~

drop后重新建表,现在表的字符集是utf8了
但是使用

$sql = "insert into tb_userinfo (username,password,email) values('sss李四','123456','lis@sina.com')";

后,插入后只显示sss,如果是纯汉字的话,什么也插不进去。

php文件另存为utf-8 无bom 格式

终于成功了,太感谢大家了。我现在练习,用的记事本创建的php文档,默认编码是ANSI。

但是每次都要这么麻烦的设置吗?
感觉mysql支持中文好麻烦。可能有的地方不需要修改我也改了,不知道哪些配置是必须修改的呢?

参考#1 版主的回复,my.ini 里面的参数都不用改,只需设置好set names utf8; 即可(当然,如果你的表是gbk,这里就为 gbk), 还有你要保证插入的数据的编码要与数据库中的编码一致才行。

人家用 utf-8 是因为他在 linux 下只能用 utf-8
你在 window 下,默认就是 gbk,搞成 utf-8 不是自找麻烦吗?

有人说用 utf-8 是为了国际化,其实有几个洋人能看懂方块字呢?

再次感谢大家,结贴散分。

Statement of this Website
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

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO) How do you prevent SQL Injection in PHP? (Prepared statements, PDO) Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

See all articles