我知道这是一个记录良好的问题,但我无法让它工作...... 请不要发送给我其他主题,我已经检查了它们,我无法得到这个东西,我无法理解为什么。
我使用此代码将数据从Android发送到PHP
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
HttpPost httpRequest = new HttpPost(
"http://example.com/myScript.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("latitude", latLng[0]+""));
nameValuePairs.add(new BasicNameValuePair("longitude", latLng[1]+""));
nameValuePairs.add(new BasicNameValuePair("altitude", alt+""));
try {
nameValuePairs.add(new BasicNameValuePair("name_comment", URLEncoder.encode(name_comment, "UTF-8").replaceAll("\'", "\\\'")));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httpRequest);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
dataObject.setResponseStatus(statusLine.getStatusCode());
Log.e(TAG, "Network error: "+statusLine.getReasonPhrase());
return dataObject;
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
Log.e(TAG, "ClientProtocolException: "+e.getMessage());
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnsupportedEncodingException: "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
//TODO Handle problems..
Log.e(TAG, "IOException: "+e.getMessage());
}
然后PHP使用此代码将数据插入到MySql表中
$keys = array_keys($_POST);
$con=mysqli_connect("example.com","user","password","database");
mysql_set_charset('utf8mb4');
mysql_query( "SET NAMES 'utf8mb4'");
$query = "INSERT INTO poi ";
$names = "(";
$values = "(";
for ($i = 0; $i < count($_POST)-1; $i++) {
$names .= $keys[$i].", ";
$values .= $_POST[$keys[$i]].", ";
}
$names .= $keys[count($_POST)-1].") ";
$values .= "'".addslashes(urldecode($_POST[$keys[count($_POST)-1]]))."') ";
$query .= $names."VALUES ".$values;
$result = mysqli_query($con,$query);
mysqli_close($con);
数据库中的TEXT编码设置为'utf8mb4_general_ci',我也尝试了不同的编码方法,但是当我尝试插入这个字符串时,我总是得到这个文字“èunpo'”:“èunpo po” “
我还返回$query
字符串以通过LogCat进行双重检查,查询为:
INSERT INTO database (latitude, longitude, altitude, name_comment) VALUES (44.10630374283182, 9.869672544300556, 32.9398994, 'è un po\' '
请不要发送给我其他主题,我已经检查了它们,我无法得到这个东西,我无法理解为什么。