Hello !

I'm trying to build a link between an applet in java and php. My applet in Java sends data to php. And then php writes data in the database. I use json object

my code in java :

public static void main(String[] args) {
    // TODO Auto-generated method stub
    JSONObject json = new JSONObject();
    json.put("json", "mkyong.com");
    //obj.put("age", new Integer(100));

    try {
    URL recup = new URL("http://localhost/json_good/recup_v2.php");
    java.net.HttpURLConnection connexion = (HttpURLConnection)recup.openConnection();
    connexion.setDoOutput(true); // Pour pouvoir envoyer des données
    connexion.setRequestProperty("Content-type", "application/json");

    //envoi de la requête
    OutputStreamWriter writer = null;
    writer = new OutputStreamWriter(connexion.getOutputStream());
    //conversion en chaine

    //#2 lecture de la réponse
    BufferedReader reader=null;
    reader = new BufferedReader(new InputStreamReader(connexion.getInputStream()));
    String ligne;

    while ((ligne = reader.readLine()) != null) {

    } catch (Exception e) {
        System.out.println(" exception : " + e.getMessage());


My code in php to receive data :

  mysql_connect('localhost', 'root', '');
  echo 'OK';
  $raw_json = json_decode($json,true);
  echo $raw_json["json"];
  mysql_query('insert into tb_user(name, surname, email) values ("'.$var.'", "'.$var.'", "'.$var.'")');

Well the link between java and php works but when I add a request to write my data in my database it doesn't work. Why ? Help me please


Do you get any errors at all during your attempt to insert?

Member Avatar


Don't use this php to insert data to your db. Not safe. Use PDO or mysqli and prepared statements. Example...

$stmt = $db->prepare("INSERT INTO tb_user (`name`, `surname`, `email`) VALUES (:var1, :var2, :var3)");
$stmt->execute(array(":var1"=>$var1, ":var2"=>$var2, ":var3"=>$var3));

there is no errors...
I will try with PDO but what is $db ?

if I write


with your code.
the result is :


OK<br />
<b>Fatal error</b>:  Call to a member function prepare() on a non-object in <b>C:\Users\lucile\Desktop\PROJET 2A\logiciels\serveruXAMPPdossier\htdocs\json_good\recup_v2.php</b> on line <b>8</b><br />

why ?

Thanks for your answers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.