简体   繁体   English

如何在php中读取json数组

[英]how to read json array in php

i am trying to read my android-data in php and insert it into two different tables (one table with common data and one table with every item in array). 我试图在php中读取我的android-data并将其插入到两个不同的表中(一个表包含公共数据,一个表包含数组中的每个项目)。 Inserting the common data into the orders table works fine, the array data does not. 将公共数据插入orders表可以正常工作,而数组数据则不能。

Here is my android-code with my basicNameValuePairs: 这是带有我的basicNameValuePairs的android代码:

ArrayList<ShoppingCardArticle> shoppingCardArticles = UsingSharedPrefs.getShoppingCard();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            TextView time = (TextView)findViewById(R.id.textView1);
            String stringTime = time.getText().toString();
            int amount = shoppingCardArticles.size();
            String sAmount = Integer.toString(amount);
            double fullprice = 0;
                for(int a=0;a<shoppingCardArticles.size();a++) {
                    double price = shoppingCardArticles.get(a).getArticlePrice();
                    int quant = shoppingCardArticles.get(a).getArticleQuantity();
                    price = price * quant;
                    fullprice = fullprice + price;
                }
            String sFullprice = Double.toString(fullprice);
            nameValuePairs.add(new BasicNameValuePair("fullprice", sFullprice));
            nameValuePairs.add(new BasicNameValuePair("amount", sAmount));
            nameValuePairs.add(new BasicNameValuePair("time", stringTime));

            for(int i = 0; i<shoppingCardArticles.size(); i++) {
                String proid = Integer.toString(shoppingCardArticles.get(i).getArticleId());
                String proquan = Integer.toString(shoppingCardArticles.get(i).getArticleQuantity());


                nameValuePairs.add(new BasicNameValuePair("proid[]", proid));
                nameValuePairs.add(new BasicNameValuePair("proquan[]", proquan));
            }

            JSONParser jsonParser = new JSONParser();
            JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", nameValuePairs);
            return null;

And this is my php-code: 这是我的php代码:

$lastIdSql = "SELECT orderID FROM orders ORDER BY orderID DESC LIMIT 1";
$lastID = mysqli_query( $mysqli, $lastIdSql );
if ( ! $lastID ) {
    @die(@mysqli_error());
}
$lastIDi = mysqli_fetch_array($lastID);
$lastIDii = $lastIDi['orderID'];
$ordDynID = $lastIDii + 1; 

$fullprice = $_POST['fullprice'];
$amount = $_POST['amount'];
$time = $_POST['time'];

$queryOrd = "INSERT INTO orders (userID, fullprice, orderTime, amount, ordDynID) VALUES ('1', '$ordFullPrice', '$ordTime', '$ordAmount', '$ordDynID')";

if ($mysqli->query($queryOrd) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $queryOrd . "<br>" . $mysqli->error;
}

$proID = array($_POST['proid']);
$proQuan = array($_POST['proquan']);

foreach($proID as $item) { 
    $productid = $item['proid']; 
    $productquantity = $item['proquan'];

    $query = "INSERT INTO ordersproducts (ordID, proID, proQuan) VALUES ('$ordDynID', '$productid', '$productquantity')";

    if ($mysqli->query($query) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $query . "<br>" . $mysqli->error;
    }
}
$mysqli->close();

So my question is, am i doing something wrong while reading the data in my php-file or is it a problem in my android-code? 所以我的问题是,在读取php文件中的数据时我做错什么了吗?还是我的android代码有问题?

Thanks in advance 提前致谢

Cheers 干杯

I'm not an android developer, but I can help you debug it in your PHP code. 我不是android开发人员,但是我可以帮助您在PHP代码中对其进行调试。 First of all, can you do a var_dump($_POST) and tell me the output? 首先,您可以执行var_dump($ _ POST)并告诉我输出吗?

I can see that you're using json_decode wrong, it looks like you're trying to use it for each key value pair instead of the full json text. 我可以看到您使用的json_decode错误,似乎您要为每个键值对而不是完整的json文本使用它。 The way it works (check http://php.net/manual/en/function.json-decode.php for more information is that you pass it a full json text (ie '{ "a":1, "b":2 }') and it translates it to POPO (Plain old PHP object) that can be accessed this way 它的工作方式( 有关更多信息 ,请参见http://php.net/manual/zh-CN/function.json-decode.php,是您将其传递了完整的json文本(即'{“ a”:1,“ b” :2}'),并将其转换为POPO(普通的旧PHP对象),可以通过这种方式访问

$object = json_decode('{ "a":1, "b":2 }');
$a = $object->a; // $a = 1
$b = $object->b; // $b = 2

When you post arrays by name in your Android code like proID[] and proQuan[] . 当您在Android代码中按名称发布数组时,例如proID[]proQuan[] The $_POST['proid'] and $_POST['proquan'] are already arrays. $_POST['proid']$_POST['proquan']已经是数组。 It's similar to a html form having several inputs with the name with square brackets ie.( <input type="text" "name="proid[]" value="" /> ) So you just assign it like this. 它类似于html表单,具有多个带有方括号名称的输入,即。( <input type="text" "name="proid[]" value="" /> ))因此,您只需像这样分配它即可。

$proID = $_POST['proid'];
$proQuan = $_POST['proquan'];

And assuming the elements in $proID and $proQuan are correctly mapped to each other. 并假定$proID$proQuan中的元素正确地相互映射。 A for loop is more suitable to iterate through the arrays. for循环更适合遍历数组。

for ($i = 0; $i < count($proID); $i++) {
    $productid = $proID[$i]; 
    $productquantity = $proQuan[$i];
    //your insert goes here

}

And of course I should tell you about the SQL Injection vulnerability in your PHP code. 当然,我应该告诉您有关PHP代码中的SQL Injection漏洞的信息。 Use prepared statement and parameter binding to prevent that. 使用准备好的语句和参数绑定来防止这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM