如何使用 PHP 在 MySQL 中存储“€"符号?

2022-01-04 00:00:00 variables utf-8 scope php mysql

我已将 PHP 字符集设置为 utf-8:

I've set the PHP character set to utf-8:

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

我已将 MySQL 中的 currency 列设置为 varchar(1) 并带有 utf8_unicode_ci 归类.

I've set the currency column in MySQL to varchar(1) with collation utf8_unicode_ci.

但是,PHP 中的以下代码:

However, the following code in PHP:

$currency = '€';
$sql = "UPDATE myTable SET currency = '$currency' WHERE user = '$user'";
mysql_query($sql);

在 MySQL 中产生以下字符:

Produces the following character in MySQL:

â

如何让 符号正确存储在 MySQL 中?

How can I get the symbol to store properly in MySQL?

推荐答案

确保你的脚本文件,包含行的文件

Make sure your script file, the file that contains the line

$currency = '€';

是 UTF-8 编码的.您应该在编辑器或 IDE 的另存为"对话框中提供一个选项来实现该效果.

is encoded UTF-8. You should have an option to that effect in your editor's or IDE's "Save as" dialog.

然后确保您的连接也是 UTF-8 编码的 - 默认情况下是 ISO-8859-1.

Then make sure your connection is UTF-8 encoded as well - it is ISO-8859-1 by default.

连接数据库后,对于mySQL之前 5.0.7:

After connecting to the database, for mySQL before 5.0.7:

mysql_query("SET NAMES utf8");

对于 mySQL 5.0.7 及更新版本:

For mySQL 5.0.7 and newer:

mysql_set_charset("utf8");

相关文章