1

Referring to various examples over stack, I wrote below code to send data to MySQL server table, but nothing is uploading there. Here is code for my Android method.

 public void sendtoserver(final String data) {
        Log.e("LWFAB", "Sending Data to Server");
        //Send data to server now
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL bulkdataurl = new URL("http://myphp.php?");
                    HttpURLConnection bulkcon = (HttpURLConnection) bulkdataurl.openConnection();
                    bulkcon.setConnectTimeout(15000);
                    bulkcon.setReadTimeout(15000);
                    bulkcon.setRequestMethod("POST");
                    bulkcon.setDoOutput(true);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(bulkcon.getOutputStream());
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(bufferedOutputStream));
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    bufferedOutputStream.close();
                    bulkcon.connect();
                    //OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bulkcon.getOutputStream());
                    //outputStreamWriter.write(data);
                    //outputStreamWriter.flush();

                    //Get Server Response
                    BufferedReader bufferedReader;
                    bufferedReader = new BufferedReader(new InputStreamReader(bulkcon.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line = null;

                    while ((line = bufferedReader.readLine()) != null) {
                        stringBuilder.append(line + "\n");
                    }
                    System.out.println(stringBuilder.toString());
                    bufferedReader.close();

                    System.out.println("Sending Bulk Data " + bulkcon);


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

    }
}

I m not getting any error. Below is my php code

<?php
require_once("../dbconnect.php"); 

$json = file_get_contents('php://input');
$obj = json_decode($json, true);
error_log(print_r($obj, true));
$array_data = $obj["data"];
print_r($obj["data"]);


foreach ($array_data as $row) {
    print_r($row);
    $sql = "INSERT INTO test (vid, name,branch,date,time) VALUES ('" . $row["vid"] . "', '" . $row["name"] . "','".$row["branch"]."','".$row["date"]."','".$row["time"]."')";

    echo "$sql<br>";
    $conn->query($sql);
}

$conn->close();
?>

And sample of data being sent as string is as below:

{"data":[{"vid":"1","name":"raj","branch":"mech","date":"2-Sep-2017","time":"13:03:24 PM"}]}

Can u guide if there is something to fix.

Panache
  • 1,701
  • 3
  • 19
  • 33
  • 3
    [Little Bobby](http://bobby-tables.com/) says **[you may be at risk for SQL Injection Attacks](https://stackoverflow.com/q/60174/)**. Learn about [Prepared Statements](https://en.wikipedia.org/wiki/Prepared_statement) with [parameterized queries](https://stackoverflow.com/a/4712113/5827005). I recommend `PDO`, which I [wrote a function for](http://paragoncds.com/grumpy/pdoquery/#function) to make it extremely easy, clean, and more secure than using non-parameterized queries. Also, [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) may help you choose between `MySQLi` and `PDO` – GrumpyCrouton Oct 02 '17 at 12:47
  • @GrumpyCrouton +1 – Yamen Nassif Oct 02 '17 at 12:48
  • 3
    Also note that the data you have shown is not valid json, the strings are not quoted. So `$obj ` will always be empty. – jeroen Oct 02 '17 at 12:48
  • @jeroen I added method used to create string, probably u can guide there why I m getting wrong format. Ur input is valid. – Panache Oct 02 '17 at 12:57
  • 1
    @Panache https://stackoverflow.com/questions/10329500/sqlite-how-to-get-string-items-using-cursor check this, you need the getString not getInt – Yamen Nassif Oct 02 '17 at 13:02
  • @Yamen u means whatever I have like int or string or double in SQLite, I will always use getString to get write format? – Panache Oct 02 '17 at 13:04
  • 1
    JSON is almost always a string, so yes – Yamen Nassif Oct 02 '17 at 13:06
  • And also be carefull about what @GrumpyCrouton said SQL Injection is obvious here. – Yamen Nassif Oct 02 '17 at 13:07
  • @Panache Numbers as values are fine in json, strings ("normal" strings, dates and times in your example) need to be quoted. – jeroen Oct 02 '17 at 13:11
  • @jeroen pls guide now as data string issue has fixed. Still no data in server – Panache Oct 02 '17 at 13:44

1 Answers1

3

You are using cursor.getInt(1) which will return an integer from the cursor. You need to use cursor.getString() in Order to get the string and put them correctly in JSON.

This is a small example:

jsonObject.put("vid", curser.getString(cursor.getColumnIndex("vid")));
Yamen Nassif
  • 2,416
  • 2
  • 24
  • 48
  • now getting correct format of json, still no data being uploaded? what else left, ps guide. – Panache Oct 02 '17 at 13:09
  • 1- check the URL. is it public ? accissable ? 2- check the connect to db try to add something like this to make sure you are connected : $con = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB'); 3- try to add some headers URLConnection.setRequestProperty("Content-Type", "application/json"); 4- echo something on the server to see if you are recieving the request or not: echo json_encode($json)); – Yamen Nassif Oct 02 '17 at 13:22
  • glad to help :). – Yamen Nassif Oct 02 '17 at 14:04