setting utf8 with mysql through php

五迷三道 提交于 2019-12-29 09:21:50

问题


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);
    }

回答1:


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.




回答2:


  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



来源:https://stackoverflow.com/questions/624301/setting-utf8-with-mysql-through-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!