且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将html实体转换为utf-8并将其插入到mysql数据库中

更新时间:2022-12-29 16:47:49

如您在脚本中所看到的,您正在指示浏览器使用UTF8.这是第一步.

As you see in your script, you are instructing the browser to use UTF8. That is the first step.

但是您的数据库需要相同的东西,并且表上的编码/排序规则也必须为UTF8.

However your database needs the same thing and also the encoding/collation on the tables need to be UTF8 too.

您可以使用utf8_general_ciutf8_unicode_ci作为排序规则来重新创建表,或者转换现有表(请参见

You can either recreate your tables using utf8_general_ci or utf8_unicode_ci as the collation, or convert the existing tables (see here)

您还需要确保您的数据库连接(即与mysql的php代码)正在使用UTF8.如果您使用的是PDO,那么会有很多文章介绍如何做到这一点.最简单的方法是:

You need to also make sure that your database connection i.e. php code to mysql is using UTF8. If you are using PDO there are plenty of articles that show how to do that. The simplest way is to do:

$mysqli->query('SET NAMES utf8');

注意,您现在要进行的更改是最终更改.如果更改数据库的连接编码,则可能会影响现有数据.

NOTE The change you will make now is final. If you change the connection encoding to your database, you could affect existing data.

EDIT 您可以执行以下操作来设置连接

EDIT You can do the following to set the connection

$mysqli = new mysqli($host, $user, $pass, $db);

if (!$mysqli->set_charset("utf8")) {
   die("Error loading character set utf8: %s\n", $mysqli->error);
}

$mysqli->close();

感兴趣的链接:

是否使用"SET NAMES"