Cannot properly insert greek characters in mysql database

后端 未结 5 2065
一生所求
一生所求 2020-12-11 05:52

Our mysql database shows Î Î¿Î»Ï Î³Î»Ï…ÎºÏŒÏ in place of greek characters while sending data from an emulator to a mysql database. Other characters are left ok.

5条回答
  •  死守一世寂寞
    2020-12-11 06:33

    Your whole php/mysql setup seems to be encoded with utf-8, but the java code isn't, starting from there:

    httpClient = new DefaultHttpClient();
    httpPost = new HttpPost(params[0]);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    

    First, the DefaultHttpClient class seems to be deprecated. However, docs say that

    This class sets up the following parameters if not explicitly set:

    • ContentCharset: HTTP.DEFAULT_CONTENT_CHARSET

    The http default charset is ISO-8859-1 according to the java constant field values

    The HttpPost itself does not appear to mingle with character sets.

    But the UrlEncodedFormEntity does. Also from the docs:

    UrlEncodedFormEntity(Iterable parameters)
    Constructs a new UrlEncodedFormEntity with the list of parameters with the default encoding of HTTP.DEFAULT_CONTENT_CHARSET
    

    Since ISO-8859-1 can't keep greek characters, passing them through those instances will modify them, hence breaking the characters in your php code.

    All of this code seems to be deprecated, but change java to output utf-8 encoded characters:

    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setContentCharset(httpParams ,"UTF-8");
    httpClient = new DefaultHttpClient(httpParams);
    httpPost = new HttpPost(params[0]);
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
    

    and remove redundancy in your php:

    ini_set("default_charset", "UTF-8");
    header('Content-type: text/html; charset=UTF-8');
    mb_internal_encoding('UTF-8');
    mb_http_input("utf-8");
    

    Header will overwrite the ini_set, so you can remove it, and the http input is already in utf8 (since we just transformed it in java), so you can remove it too:

    header('Content-type: text/html; charset=UTF-8');
    mb_internal_encoding('UTF-8');
    

提交回复
热议问题