JSON对象数组写入到PHP然后到数据库

JSON对象数组写入到PHP然后到数据库

问题描述:

我需要将我在我的模拟器上创建的整个数据库发送到我的服务器。刚刚了解了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个对象发送?

谢谢!

像这样的东西应该工作:

$json = file_get_contents('php://input'); 

// Decode into array instead of stdclass 
$arr = json_decode($json, true); 

// Loop each object in the outer array 
foreach ($arr as $obj) { 
    $comment = $obj['comment']; 
    $category = $obj['category']; 
    $sql = "INSERT INTO test1 (comment, category) VALUES ('$comment', '$category')"; 
} 
+0

我代替我的就是我上面写的与您的并没有什么PHP部分代码被发布到我的数据库:( – Pam

+0

@Pam它不是整个代码,它的作用是为了说明,这个想法是有一个循环,然后在循环中做你已经做的事情,这应该为每个对象插入一个新行。 – OptimusCrime