更新mysql 编码,在插入错误的编码后更新MySQL数据库中的数据

I am using PHP and MySQL for saving Arabic data.

My database collation is : utf8_general_ci

My database Character set is : utf8

At first I did not use SET NAMES utf8 before insertion so the data was inserted in strange characters in the database but was displayed properly in my application. After using SET NAMES utf8, data is inserted properly but the old data is not displayed in Arabic characters even in my application (The new data is ok) .

How can I update all the data to be displayed in Arabic letters in both my application and MySQL database?

Update

When I check the encoding of the both of strings ( the one that is inserted and the one that I want to convert to ) using mb_detect_encoding function I get that both of the strings are UTF-8 .

Here is an example of the two strings :

the text inserted : الإسم بالعربية

the text I need to convert to : الإسم بالعربية

解决方案

You suffer from "double encoding".

Here's what happened.

The client had characters encoded as utf8; and

SET NAMES latin1 lied by claiming that the client had latin1 encoding; and

The column in the table declared CHARACTER SET utf8.

Let's walk through what happens to e-acute: é.

The hex for that, in utf8 is 2 bytes: C3A9.

SET NAMES latin1 saw it as 2 latin1-encoded characters à and © (hex: C3 and A9)

Since the target was CHARACTER SET utf8, those 2 characters needed to be converted.

à was converted to utf8 (hex C383) and © (hex C2A9)

So, 4 bytes were stored (hex C383C2A9)

When reading it back out, the reverse steps were performed,

and the end user possibly noticed nothing wrong. What is wrong:

The data stored is 2 times as big as it should be (3x for Asian languages).

Comparisions for equal, greater than, etc may not work as expected.

ORDER BY may not work as expected.

Something like this will repair your data:

UPDATE ... SET col = CONVERT(BINARY(CONVERT(

CONVERT(UNHEX(col) USING utf8)

USING latin1)) USING utf8);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值