0

I had previously encoded MySQL data in latin1. Now, I've converted it to UTF-8 in MySQL but the data is still saved in latin1. UTF-8 data that was originally stored as Latin-1 has not converted correctly to UTF-8. I need a work around in PHP, so that when I get data from the database using a query, it should be converted into UTF-8.

I found a solution to convert the database using a MySQL function, which is really helpful... MySQL - Convert latin1 characters on a UTF8 table into UTF8

But my scenario is, I need to do this in PHP.

Community
  • 1
  • 1
Haroon
  • 155
  • 2
  • 10
  • Have you tried [`mb_convert_encoding`](http://php.net/manual/en/function.mb-convert-encoding.php)? – Ronald Paul Mar 27 '13 at 15:52
  • Or just [`utf8_encode`](http://www.php.net/manual/en/function.utf8-encode.php) – Marcel Gwerder Mar 27 '13 at 15:56
  • Beside from other changes that might being required, you'll have to issue `SET names UTF8` as the first command after connecting to mysql. This is important! – hek2mgl Mar 27 '13 at 15:56

1 Answers1

0

You can use PHP functions utf8_encode (http://php.net/manual/fr/function.utf8-encode.php) and utf8_decode (http://php.net/manual/fr/function.utf8-decode.php)

Then you have to loop in your SQL tables to replace values with sanitized ones

<?php
$query = mysql_query("SELECT * from table");

while($result = mysql_fetch_array($query)){
    //Then update row with new name
    mysql_query("UPDATE table SET col_name = '" . utf8_decode($result["col_name"]) ."' WHERE id = " . $result["id"]);

  }
?>
Pouki
  • 1,654
  • 12
  • 18