How to convert wrongly encoded data to UTF-8 in MySQL?

MySQLMySQLi Database

You need to use CONVERT() function along with binary keyword. The syntax is as follows −

SELECT CONVERT(binary CONVERT(yourColumnName using latin1) USING UTF8) as anyAliasName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table UtfDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(15),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using INSERT command. The query is as follows −

mysql> insert into UtfDemo(Name) values('Obama’s');
Query OK, 1 row affected (0.28 sec)
mysql> insert into UtfDemo(Name) values('John’s');
Query OK, 1 row affected (0.23 sec)
mysql> insert into UtfDemo(Name) values('Carol’s');
Query OK, 1 row affected (0.15 sec)
mysql> insert into UtfDemo(Name) values('Sam’s');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from UtfDemo;

The following is the output −

+----+----------------+
| Id | Name           |
+----+----------------+
|  1 | Obama’s      |
|  2 | John’s       |
|  3 | Carol’s      |
|  4 | Sam’s        |
+----+----------------+
4 rows in set (0.00 sec)

Here is the query to convert wrongly encoded data to UTF8 −

mysql> select CONVERT(binary CONVERT(Name using latin1) using utf8) as ListOfName from UtfDemo;

The following is the output −

+------------+
| ListOfName |
+------------+
| Obama’s    |
| John’s     |
| Carol’s    |
| Sam’s      |
+------------+
4 rows in set, 1 warning (0.00 sec)
raja
Published on 26-Feb-2019 17:52:08
Advertisements