如何从MySQL获取数据并使用PHP脚本和JSON将其存储到Java程序

时间:2013-12-19 22:09:31

标签: java php mysql json

我想创建Java应用程序,它将从MySQL接收数据并将其存储到列表中,但是开始存储到JTextArea就可以了。

我在localhost上有表格的数据库,以及激活后的PHP脚本,从表“orders”获取数据并以JSON格式返回数据。

<?php
    /*
 * Following code will list all orders
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from orders table
$result = mysql_query("SELECT* FROM orders") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["orders"] = array();

    while ($row = mysql_fetch_array($result)) {
        // temp user array
        $order = array();
        $order["id"] = $row["id"];
        $order["tablle"] = $row["tablle"];
        $order["drink"] = $row["drink"];
        $order["created_at"] = $result["created_at"];

        // push single product into final response array
        array_push($response["orders"], $order);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found 
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);;
}
?>

当我在localhost上测试时,它运行正常,但我不知道如何从java调用这个php脚本并将该文本格式化为JSON并将其存储在Java中的JTextArea中。

我对JSON知之甚少。对不起,诺布在这里。

Java类:

package newpackage;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Prozor extends JFrame implements ActionListener{

    JPanel panel = new JPanel();
    JPanel panel2 = new JPanel();
    JTextArea ta = new JTextArea();
    JButton dugme = new JButton("Get data");

    public Prozor(){
        this.setBounds(500, 200, 500, 500);
        this.setTitle("naslov");
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().add(panel, BorderLayout.NORTH);
        this.getContentPane().add(panel2, BorderLayout.SOUTH);

        panel.setLayout(new FlowLayout(FlowLayout.CENTER));
        panel2.setLayout(new FlowLayout(FlowLayout.CENTER));

        ta.setPreferredSize(new Dimension(450,400));
        panel.add(ta);
        panel2.add(dugme);

        dugme.addActionListener(this);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource().equals(dugme)) {

        }
    }

    public static void main(String[] args) {
        Prozor p = new Prozor();
        p.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:0)

你需要做的一些事情。

  1. 从Java调用php脚本

    要执行此操作,您需要知道脚本的网址,包括protocolporthostpath。换句话说,就像:http://localhost:8000/orders.php。获得网址后,您需要make an HTTP request

  2. 将响应解析为JSON数据结构。

    您可以使用Jackson

  3. 等现有库来执行此操作
  4. 使用JSONObject填充您的用户界面

    了解您希望如何显示数据,并在setText

  5. 上致电JTextArea