MySql UTF8 collation data with accents not displayed properly when PHP fetched

為{幸葍}努か 提交于 2020-01-15 11:51:22

问题


I am fetching some data having UTF8 collation (utf8_unicode_ci) from a MySQL database with PHP. I am using this piece of code:

function advancedDatabaseSearch($pattern, $lpref) {

    $link = mysql_connect(DB_URL, DB_USER, DB_PWD);

    if (!$link) {
        return 'Could not connect: ' . mysql_error();
    }

    $esc_value = mysql_real_escape_string($pattern);
    $esc_lpref = mysql_real_escape_string($lpref);

    mysql_select_db(DB_NAME, $link);

    $query = "SELECT RAWVALUE FROM rawvalueitem "
        ."WHERE RAWVALUE LIKE '".$esc_value."' "
        ."AND LANGUAGE = '".$esc_lpref."' "
        ."ORDER BY RAWVALUE ASC";

    $result = mysql_query($query);

    $return = "";

    while($row = mysql_fetch_array($result)) {
        $return = $return.$row['RAWVALUE']." ";
    }

    mysql_close($link);

    return $return;

}

and then from the php called by Ajax:

$result = advancedDatabaseSearch($tttmp, $lpref);
echo $result;
return;

Yet, when I display the result in a text area, the accents are not displayed properly:

On the other side, when I fetch UT8 data from a file:

if ( $file_loc != NULL ) {
    if ( file_exists($file_loc) ) {
        $handle = fopen($file_loc, "rb");
        $contents = fread($handle, filesize($file_loc));
        fclose($handle);
        $result = $contents;
    }
}

echo $result;
return;

I don't get this issue !!! How can I solve it when using PHP to fetch data from MySql?


回答1:


Did you set UTF-8 as the default character set of your database connection?

mysql_set_charset('utf8', $link);

http://www.php.net/manual/en/function.mysql-set-charset.php

Also, does your page have a <meta> tag with the correct character set?




回答2:


This is working like a.. you now!

<?php
    $config_db_server='localhost';
    $config_db_server_username='root';
    $config_db_server_password='';
    $config_db_database='test';
    $config_db_charset='utf8';
    $config_db_collation='utf8_general_ci';
    $config_table_prefix='class_';
    $config_live_site='http://localhost';
    $config_abs_path='C:\xampp\htdocs';
    $config_debug=0;

    $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password);
    mysql_query("SET character_set_results=utf8", $dbLink);
    mb_internal_encoding('utf8');
    mysql_query("set names 'utf8'",$dbLink);

?>

Change here your db connect: ( $dbLink = mysql_connect($config_db_server, $config_db_server_username, $config_db_server_password); )



来源:https://stackoverflow.com/questions/9968438/mysql-utf8-collation-data-with-accents-not-displayed-properly-when-php-fetched

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