1

I have the following very simple code, which retrieves utf8 formatetd data, such as containing umlauts from a mysql database, which may or may not be set as utf8. If I use either of the commented out approaches to ensure that utf8 data is returned, the data will NOT be returned as utf8, however if I leave them off, the data will be displayed. Why would forcing utf8 negate displaying data as utf8?

<?php
  $con = mysqli_connect("localhost", "x", "", "x");
  //$con->query("SET NAMES 'utf8'");
  //$con-set_charset('utf8');
  $recordsQuery = "SELECT ARTICLE_NAME FROM AUCTIONS1";

  if ($getRecords = $con->prepare($recordsQuery)) {
        $getRecords->execute();
        $getRecords->bind_result($ARTICLE_NAME);

        while ($getRecords->fetch()) {
        echo "<p>$ARTICLE_NAME";
             }
    } else {
        print_r($con->error);
    }
Joshxtothe4
  • 4,061
  • 10
  • 53
  • 83
  • if it's not returned in UTF-8, please show samples (including hex decodes if at all possible) of how it _is_ returned! – Alnitak Mar 08 '09 at 21:18
  • and also check that your tables are actually configured to use UTF-8 collation – Alnitak Mar 08 '09 at 21:18
  • the latter would be irrelevant .. the point of "SET NAMES" is exactly that MySql will convert if appropriate. – troelskn Mar 08 '09 at 23:26
  • My tables are not set to use UTF-8 collation in this case, and so I though SET NAMES would ensure it was utf8. However, with SET NAMES enabled, it does not display as utf8. How can I show the differences in what is displayed? –  Mar 09 '09 at 10:22

2 Answers2

3

Perhaps the error lies in the charset you're serving the page with. If you're getting UTF-8 content out of the database and serving it with the default HTML charset of Windows-1252 then it's going to look garbled. Make sure you have the equivalent of this:

header( 'Content-Type: text/html; charset=utf-8' );

in your PHP code.

staktrace
  • 488
  • 3
  • 7
  • This is not in the test code I provided, but is set in my ajax application. The resulting page is definitely utf8, but if I set names utf8 the data displays garbled. –  Mar 09 '09 at 10:21
0
  1. Make sure your data is already UTF-8 encoded in your database
  2. configure database to deliver UTF-8 (eg. SET NAMES 'utf8')
  3. use the right encoding on your website (nod to stak)

If you still have problems, please provide more data, especially what is expected and what finally delivered

Peter Parker
  • 29,093
  • 5
  • 52
  • 80
  • It doesn't really matter what encoding is used to store the strings in the database, since most encodings (including the default iso-8859-1) can represent u-umlaut. MySql is charset aware, so it will convert to utf-8, if the connection is set to utf-8. – troelskn Mar 08 '09 at 23:33