[英]How to get data from MySQL and store it to Java program using PHP script and JSON
我想創建一個Java應用程序,該應用程序將從MySQL接收數據並將其存儲到列表中,但是對於開始存儲到JTextArea來說會很好。
我在本地主機上有帶表的數據庫,還有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);;
}
?>
當我在本地主機上對其進行測試時,它可以正常工作,但是我不知道如何從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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.