sadegh
sadegh

Reputation: 1642

Android: Sent UTF-8 data to MySQL

I save data to mysql db with php and json but my data convert to ? ,I use utf-8 in php and db connect and java code

php

<?php
header("Content-type: application/json; charset=utf-8");
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');

$hostname='localhost';
$username='ekht3r44_6785h5h';
$password='IFVB!8Nw{#-S';
$response = array();

.
.
.
$dbh=new PDO("mysql:host=$hostname;dbname=db;charset=utf8mb4",$username,$password);

$sql="INSERT INTO contact_form (name,email,subject,message) VALUES (".$_POST['name'].",".$_POST['email'].",".$_POST['subject'].",".$_POST['message'].");";

$statement = $dbh->prepare("INSERT INTO contact_form (name,email,subject,message) VALUES (:name,:email,:subject,:message);");
$statement->execute(array(':name' => $_POST['name'],':email' => $_POST['email'],':subject' => $_POST['subject'],':message' => $_POST['message']));
.
.
.
?>

java

protected String doInBackground(String... args) {
    try {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", et_name.getText().toString()));
        params.add(new BasicNameValuePair("email", et_email.getText().toString()));
        params.add(new BasicNameValuePair("subject", et_subj.getText().toString()));
        params.add(new BasicNameValuePair("message", et_msg.getText().toString()));
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        is.close();
        page_output = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    return page_output;
}

Can you please check where has it gone wrong.

Upvotes: 0

Views: 977

Answers (1)

RuntimeException
RuntimeException

Reputation: 1643

Please check the charset of your table in MySQL. That "might" be the cause.

Upvotes: 1

Related Questions