0
我需要將我在我的模擬器上創建的整個數據庫發送到我的服務器。剛剛瞭解了JSON。JSON對象數組寫入到PHP然後到數據庫
開始簡單的,我試過這段代碼:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("comment", "OK1");
jsonObject.put("category", "pro1");
String message = jsonObject.toString();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(message);
wr.flush();
wr.close();
和我的PHP是
$json = file_get_contents('php://input');
$obj = json_decode($json);
$comment = $obj->{'comment'};
$category = $obj->{'category'};
$sql = "INSERT INTO test1 (comment, category) VALUES ('$comment', '$category')";
,我能夠把物體進入我的表。現在我想創建一個數組,讓我可以有多個對象(我假設這是正確的方式來做到這一點?所以就像我有多個名字和年齡相同的狗,我會把它們放到一個數組,對嗎?)
我試着下面的代碼只有一個對象在我的數組中,它不會打印任何東西到我的數據庫中。我沒有改變我的PHP代碼,因爲我不知道我會改變什麼。
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try {
jsonObject.put("comment", "OK1");
jsonObject.put("category", "pro1");
jsonArray.put(jsonObject);
String message = jsonArray.toString();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(message);
wr.flush();
wr.close();
假設這是做了正確的方式,把物品放入數組,然後寫出來,我該怎麼辦,最終循環遍歷數組,如果我有2個或3個對象發送?
謝謝!
我代替我的就是我上面寫的與您的並沒有什麼PHP部分代碼被髮布到我的數據庫:( – Pam
@Pam它不是整個代碼,它的作用是爲了說明,這個想法是有一個循環,然後在循環中做你已經做的事情,這應該爲每個對象插入一個新行。 – OptimusCrime