简体   繁体   English

使用PHP在MySQL中损坏UTF8字符

[英]broken UTF8 characters in MySQL using PHP

I have noticed when dealing with some names that are not of normal spelling ie standard alphabet UK/US are getting lost from my inserting of a record to what actually shows up in the database. 我已经注意到,在处理一些非正常拼写的名称时,即标准字母UK / US从我将记录插入数据库中实际显示的内容中丢失了。 I have done quiet a bit of reading regarding the Collation type, which is what I thought was causing the issue, but not sure if this is the case or I'm still doing it wrong as my problem is still persisting. 我已经对有关归类类型的内容进行了一些静默的阅读,这是我认为引起问题的原因,但是不确定是否是这种情况,或者由于我的问题仍然存在,我还是做错了。

Below is an example of a record I am creating as well as my database structure, and as you can also see the last_name field has "ö", when I lookup the record I actually see the last_name "Körner" 以下是我正在创建的记录以及数据库结构的示例,并且您还可以看到last_name字段具有“ö”,当我查找记录时,我实际上看到了last_name“Körner”

CREATE TABLE `data` (
  `id` bigint(20) NOT NULL,
  `profile_id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

ALTER TABLE `data`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `profile_id` (`profile_id`);

ALTER TABLE `data`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT;


INSERT IGNORE INTO data (profile_id, first_name, last_name) VALUES (1, 'Brent', 'Körner');

The field collation on the last_name is set to 'utf8_general_ci' which that I understand or should I say thought would sort this issue out. 我了解或应该说可以解决此问题的last_name字段排序规则设置为“ utf8_general_ci”。

This seems to be something I am doing wrong / missing with PHP, as when I execute the INSERT query within PhpMyAdmin it saves fine. 这似乎是我做错了/用PHP缺少的事情,因为当我在PhpMyAdmin中执行INSERT查询时,它可以很好地保存。

it seems the issue was down to PHP in the end, and i wasn't setting the charset. 看来问题最终归结于PHP,而我没有设置字符集。

For mysql 对于mysql

mysql_set_charset('utf8');

For mysqli 对于mysqli

mysqli_set_charset('utf8');

ref https://akrabat.com/utf8-php-and-mysql/ 参考https://akrabat.com/utf8-php-and-mysql/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM