0
我想創建Java應用程序,它將從MySQL接收數據並將其存儲到列表中,但是一開始存儲到JTextArea會很好。如何從MySQL獲取數據並將其存儲到使用PHP腳本和JSON的Java程序中
我有本地數據庫和本地主機上的表和PHP腳本,當它激活時,從表「訂單」獲取數據並返回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格式的文本,並將其存儲在JTextArea中使用Java。
我對JSON瞭解不多。對不起,這裏點菜。
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);
}
}
我想你需要一個Java客戶端連接到提供php輸出的服務器。如果你做了一些研究,你可以找到數百個圖書館和方法。 – zapl
不要使用任何'success'鍵,只是在沒有結果時編碼空數組('[]')^^ – moonwave99