3

I'm currently developing an Android application for a small project which consists in learning development on Android platform. I already did all the app and now I need to send data from the app to a server in PHP with MySQL database. I have a web service to make the insert in the database from data sent through a json format. I have tested the web service with Advanced Rest Client and I have succeeded in inserting data into my database. Now I'm testing from my android app application but it doesn't work. I have checked the connection status and it is "OK" but when I check the database, there is no insertion.

Below is my web service in PHP:

<?php  

$json = file_get_contents('php://input');
$obj = json_decode($json);
$con = mysql_connect('host','login','password') 
   or die('Cannot connect to the DB');
mysql_select_db('database_name',$con);
mysql_query("INSERT INTO `commercial` (firstName, surNameC, email, number, salonName, uuid)
VALUES ('".$obj->{'firstname'}."','".$obj->{'name'}."','".$obj->  {'email'}."','".$obj->{'phonenumber'}."','".$obj->{'fairreference'}."','".$obj-> {'commercialuuid'}."')");
mysql_close($con);

$posts = "INSERTION OK";
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts)); 

?>

And the sending process from the android side:

    URL url;
    HttpURLConnection urlConnection;
    StringBuilder strBuilder;
    try {
        url = new URL(URL);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.connect();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commercialuuid", args[0]);
        jsonObject.put("name", args[1]);
        jsonObject.put("firstname", args[2]);
        jsonObject.put("phonenumber", args[3]);
        jsonObject.put("email", args[4]);
        jsonObject.put("fairreference", args[5]);

        Log.d("json", jsonObject.toString());
        Log.d("request", "starting");

        OutputStreamWriter writer = new   OutputStreamWriter(urlConnection.getOutputStream());
        writer.write(jsonObject.toString());
        writer.flush();

        Log.e("connection status",urlConnection.getResponseMessage());

        //get the response from the web service
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        strBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            strBuilder.append(line);
        }
        writer.close();
        reader.close();
        urlConnection.disconnect();
        return null;

    } catch (Exception e) {
        e.printStackTrace();
    }

As I have searched for several threads that have been validated and based my work on it, I really don't understand why it doesn't work. I would be grateful if anyone could help me.

Thanks.

4
  • As a first step, capture the result of mysql_query(), take a look at this: github.com/dmnugent80/ShareAppServerSide/blob/master/… Commented Nov 19, 2015 at 19:08
  • Thanks for the advice. I did it, it is quite useful. Now I have some advancement, I insert but there are no values in the inserted object. Commented Nov 19, 2015 at 20:34
  • I have printed the json I receive in the web service and it is empty. So, the problem is the way I send the json to the web service. Is there another way that using outputstreamwriter ? Because I checked the json on Logcat and it is well created and formatted. Commented Nov 19, 2015 at 20:51
  • Problem solved! It was totally from the free server I was using... buyethost... I have tested it on a local wamp server and I works! Commented Nov 19, 2015 at 21:39

1 Answer 1

2

-->Update: As the comments say, this answer is now deprecated and your only choice is to use the lib Retrofit, im using it now without problems. look for it and i recomend using Retrofit2 instead of the older one.||

You can use $post to send your just de data you want to insert

insert it into a thread or an async task

List<NameValuePair> querypair=new ArrayList<NameValuePair>(1);
                        DefaultHttpClient httpClient = new DefaultHttpClient();;
                        querypair.add(new BasicNameValuePair("id", id));
                        querypair.add(new BasicNameValuePair("name", name));
                        querypair.add(new BasicNameValuePair("email", email));
                        HttpPost httpGetquery =new HttpPost("http://www.youradddres/insert.php");
                        httpGetquery.setEntity(new UrlEncodedFormEntity(querypair));
                        HttpResponse httpResponseGetQuery = httpClient.execute(httpGetquery);
                        httpEntityQueryGet = httpResponseGetQuery.getEntity();
                        Log.i("Entity",httpEntityQueryGet.toString());

also upload this php

<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "dbname";

$con=mysql_connect("localhost","$username","$password");
mysql_select_db("$dbname", $con);

$id=$_POST['id'];
$name=$_POST['name'];
$email=$_POST['email'];

mysql_query("INSERT INTO table(id, name, email)
VALUES ('$id', '$name', '$email')");

echo "New record created successfully";

?>

hope it helps

Sign up to request clarification or add additional context in comments.

3 Comments

also your DBuser must have privileges to do inserts!
DefaultHttpClient and BasicNameValuePair are deprecated in api 22, and removed in api 23.
Yes indeed. And now is the trend of JSON to manipulate data between platforms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.