I am trying to send JSON to php and store the data that sent but I cant make it work
my Android Code
public void sendToServer(String txt) throws JSONException{
String path = "http://10.0.0.6:8888/json.php";
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(path);
json.put("text", txt);
Log.i("jason Object", json.toString()); //This print the data perfectly
post.setHeader("json", json.toString());
post.setHeader("Accept", "application/json");
Log.i("Done", "DONE 1");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
Log.i("Done", "DONE 2");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myjson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("Done", "DONE 3");
response = client.execute(post);
/* Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); // Get the
// data in
// the
// entity
String a = convertStreamToString(in);
Log.i("Read from Server", a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
and my php code
<?php
$decoded = json_decode(stripslashes($_POST['myjson']));
if($decoded)
$con = mysql_connect('localhost','root','root')
or die('Cannot connect to the DB');
mysql_select_db('deaf',$con);
mysql_query("INSERT INTO text
VALUES ('".$decoded->{'text'}"')");
mysql_close($con);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
else
echo "error";
?>
the insert statement doesn't work , i spent hours trying to fix it , nothing worked please help me , thanks
There are a few issues with this.
myjson
working. If you do, I would change the name to something like document
. It doesn't need to be in the header, and you can remove StringEntity.stripslashes
. You should not have to run it on form input. If you do, that may mean magic_quotes
is enabled. magic_quotes has been removed from PHP (5.4 and later) and should never be used.mysql_real_escape_string
. Otherwise, you will be vulnerable to SQL injection.You can simplify the object access. So the code should be:
mysql_query("INSERT INTO text VALUES ('" . mysql_real_scape_string($decoded->text) . "')");
If the insert statement fails, please post what the errors are, including mysql_error
.