簡體   English   中英

如何將解碼后的 JSON 正確插入 Mysql 數據庫

[英]How to Properly Insert Decoded JSON to Mysql Database

我一直在互聯網上搜索如何使我的數據庫的 php 代碼正常工作,但我無法理解! 這就是為什么我別無選擇,只能問一個問題,我希望有人能在這件事上幫助我或指導我。 很感謝任何形式的幫助!

問題:我想插入一個JSON格式的數據到mysql數據庫。

Android 中的字符串請求代碼

public void insertCartProducttoDatabase() {

    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Constants.cartdata_url,
            new com.android.volley.Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (!jsonObject.getBoolean("error")) {
                            Toast.makeText(getApplicationContext(),
                                    jsonObject.getString("message"),
                                    Toast.LENGTH_LONG).show();
                            finish();
                        } else {
                            Toast.makeText(getApplicationContext(),
                                    jsonObject.getString("message"),
                                    Toast.LENGTH_LONG).show();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("response", "" + error);
        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put(KEY_VC_ARRAY, convertedArray);
            //params.put(KEY_VC_BRANCH, branchid);
            return params;
        }
    };
    RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}

logcat 結果:這是來自我的回收站視圖的數組結果

[
{
    "productname": "Siopao",
    "quantity": "3",
    "totalprice": 1500
},
{
    "productname": "Siomai",
    "quantity": "3",
    "totalprice": 297
},
{
    "productname": "Burger",
    "quantity": "4",
    "totalprice": 200
}
]

PHP 代碼 DB Operations.php (UPDATEDv2)

//INSERT CART PRODUCTS 
    public function insertIndividualCart($cartarray){
        $receivedArray = $_POST['cartarray'];
        $new_array = json_decode($receivedArray,true);
        var_dump($new_array);

        $stmt = $this->con->prepare("INSERT INTO `cart_data` (`cartid`, `productname`, `quantity`, `totalprice`, `created`) 
        VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP )");

        foreach($new_array as $row){ 

            $stmt->bind_param('ssi', $row['productname'], $row['quantity'], $row['totalprice']);

            if($stmt->execute()){
                return 1;
            }else{
                return 2;
            }
        }
    }

PHP代碼cartData.php

<?php
require_once '../DbOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
    isset($_POST['cartarray']) 
){
    //operations data
    $db = new DbOperations();

    $result = $db->insertIndividualCart(
        $_POST['cartarray']
    );

    if($result == 1){
        $response['error'] = false;
        $response['message'] = "Success";
    }elseif($result == 2){
        $response['error'] = true;
        $response['message'] = "Failed, Error Occured";
    }

}else{
    $response['error'] = true;
    $response['message'] = "Required Field are missing";
}

}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
 echo json_encode($response);

我知道我的 php 代碼 Dboperation.php 是錯誤的。 只是我不知道如何開始,我看到了一個視頻,我必須首先解碼來自 android 的數組,然后使用 foreach 並在內部使用 Insert,我無法理解的是我如何在我的數組上使用綁定參數剛剛解碼? 或者我需要嗎? 因為我的理解是為了讓我的代碼正常工作,我需要根據我在公共函數中使用的參數來使用綁定參數,對嗎? (我知道它叫什么,我所說的公共函數就像這樣一個“公共函數 insertIndividualCart($cartarray){}”)我只是一個初學者,所以對我放輕松! 我只是別無選擇,只能問,因為我真的無法理解他們在帖子中所做的事情。

這不是一個完整的答案,但它應該讓你知道你哪里出錯了。 您需要在循環內執行查詢。

public function insertIndividualCart($cartarray)
{
    $new_array = json_decode($cartarray, true);
    $stmt = $this->con->prepare("INSERT INTO `cart_data` (`cartid`, `productname`, `quantity`, `totalprice`, `created`) 
        VALUES (NULL, ?, ?, ?, CURRENT_TIMESTAMP)");

    foreach ($new_array as $row) {
        // you have 3 placeholders in SQL, so you need 3 variables bound
        $stmt->bind_param('sss', $row['productname'], $row['quantity'], $row['totalprice']);
        $stmt->execute();
    }

    return true;
}

看看它短了多少? 在循環之前准備查詢,然后在循環內綁定值並執行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM