具有国际字符串的PHP和MySQL最佳实践 [英] Best practices in PHP and MySQL with international strings

查看:62
本文介绍了具有国际字符串的PHP和MySQL最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使MySQL DB,表和字段的排序规则设置为utf8_general_ci,也经常发生将é这样的字符转换为é的情况.页面的 Content-Type 中的编码也设置为UTF8.

It often happens that characters such as é gets transformed to é, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the Content-Type for the page is also set to UTF8.

我了解utf8_encode/decode,但是我不确定在哪里以及如何使用它.

I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.

我已阅读"每个软件开发人员绝对,肯定地必须了解Unicode和字符的绝对最低要求设置(无借口!)"文章,但我需要一些MySQL/PHP特定的指针.

I have read the "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" article, but I need some MySQL / PHP specific pointers.

问题:如何确保用户输入的包含国际字符的数据不会损坏?

推荐答案

首先查看 http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet 我认为缺少了一件重要的事情(也许我忽略了这一件事). 根据您的MySQL安装和/或配置,您必须设置连接编码,以便MySQL知道您期望在客户端上使用哪种编码(意味着MySQL连接的客户端,应该是您的PHP脚本).您可以通过手动发出

On the first look at http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet I think that one important thing is missing (perhaps I overlooked this one). Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a

SET NAMES utf8

在发送到MySQL服务器的任何其他查询之前,先进行

查询.

query prior to any other query you send to the MySQL server.

如果您在PHP端使用PDO,则可以设置连接,以通过使用以下方式在每个(重新)连接上自动发出此查询:

If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using

$db=new PDO($dsn, $user, $pass);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");

初始化数据库连接时.

这篇关于具有国际字符串的PHP和MySQL最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆