0

I would like to send data from a php script to a java desktop application. The php data is retrieved from a database in a SELECT * FROM xxxxx. I would like to pass these values to java for displaying.

I know I can receive data from php in java through the following statement

String buffer;

    in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
    while((buffer = in.readLine()) != null){
        System.out.println(buffer);
    }

However what if I want to capture specific values like firstname , lastname, age, occupation etc etc. How can I do that in java not android.

Any help would be much appreciated!

3
  • 4
    use json to encode response from php server and decode it in your java code Commented Aug 4, 2015 at 7:40
  • 1
    It might be easier to set up a rest service in PHP (as shown here) and have your Java application consume the service. This would provide more structure to your application. Commented Aug 4, 2015 at 7:44
  • @npinti That might not be "easier". That's actually called: Reasonable. Commented Aug 4, 2015 at 7:55

2 Answers 2

1

Use JSON as a structure to transport your data. In you PHP script have something like this, if you are using PDO

$pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password");
$statement=$pdo->prepare("SELECT * FROM table");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;

This is the way I do it in my Android apps.

Android has JSON libraries to help you process the JSON.

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

Comments

1

Use Json to do it , first you need to get data from table

       $dbname  = "dbname";
        $host       = "localhost";
        $user       = "root";
        $pass       = "";
        $con        = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
        $select     = $con->prepare("select * from your_tablename");
        $execute    = $select->execute();
        foreach ($select as $selects) {
             $fname[]   = array("fname"=>$selects['fname']);
             $lname[]   = array("lname"=>$selects['lname']);
             $age[]     = array("age"=>$selects['age']);     
        }
        $new_array      = array_merge($fname,$lname);
        echo json_encode($new_array);

and in Java side you need to decode the json and use multi dimenssional array to retrieve the values

  eg : array[0]['fname'].

Hope it will help you

Comments

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.