简体   繁体   中英

How to Properly Insert Decoded JSON to Mysql Database

Iv been searching the internet on how to make my php code for my database works and i cant understand any of it! thats why i have no choice but to just ask a question i hope someone can help me or guide me on this matter. Any help is very much appreciated!

Question: I want to insert a JSON format data to mysql database.

String Request Code in 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 Result: This is the array result comming from my recycler view

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

PHP CODE 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 CODE 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);

I know my php code Dboperation.php is wrong. its just i dont know how to start i saw a video, that i have to decode first my array comming from android and then use foreach and inside use Insert, What i cant understand is that how can i use bind params on the array that i just decoded? or do i need to? cause what i understand is in order for my code to work i need to use bind params depending on the paramter that i used on public function right? (idk what its called what i mean by public function is like this one " public function insertIndividualCart($cartarray){} " ) im just a beginner guys so go easy on me! i just dont have any choice but to just ask since i really cant understand the things that they did in their post.

This is not a full answer, but it should give you an idea where you have gone wrong. You need to execute the query inside a loop.

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;
}

See how much shorter it is? Prepare the query before the loop and then bind values inside the loop and execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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