0

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.

  • Does this answer your question? [How to include a PHP variable inside a MySQL statement](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) – Dharman Dec 10 '19 at 06:36
  • Ty for the reply sir! i think i already know how to insert a single row to the database since i already made it on my other functions sir, my problem is on how to insert data comming from json or a multiple data sir – Nao201431688 Dec 10 '19 at 06:45
  • What is ``".$row["productname"]."`` in your SQL? Why do you have it? Why do you prepare in a loop. No, you don't know how to include variables in SQL from the looks of it.Take a look at the linked post once more. – Dharman Dec 10 '19 at 07:14
  • oh sorry sir its just in the video that how he did it and i just used it i will see the link again sir – Nao201431688 Dec 10 '19 at 07:23
  • also the loop sir i just saw it in the other post about on binding params on an array sir but i really dont know what i am doing i just tried if it is working sir can u guide me sir on how to start it? – Nao201431688 Dec 10 '19 at 07:43
  • Which other post? – Dharman Dec 10 '19 at 07:46
  • sir i updated my dp oberation code am i doing it right sir? i tried on postman i am getting error on bind params part. i based on this post sir https://stackoverflow.com/a/17398347/11467753 – Nao201431688 Dec 10 '19 at 08:23
  • sorry sir i i opened several tabs and i cant remember which one is it hahaha i already closed the tab sir the one that i based my bind params code – Nao201431688 Dec 10 '19 at 08:24
  • No, it's still completely wrong, just in another way. I don't time right now to show you how to rewrite your code, but maybe you could learn from this site https://phpdelusions.net/ – Dharman Dec 10 '19 at 08:27
  • ah nvm i solved it! i am making it hard for myself hahaha so bind params is not needed when the data comes from a json array haha all i need is to correct my insert query inside the loop and remove bind params hahahaha – Nao201431688 Dec 10 '19 at 15:26
  • You need bind_params. If you say you don't, it means that you are still doing something wrong. – Dharman Dec 10 '19 at 15:26
  • really? but why is it i tried posting data through postman and it successfully entered the data to my database? – Nao201431688 Dec 10 '19 at 15:27
  • https://ibb.co/RYgtjGf my output on postman – Nao201431688 Dec 10 '19 at 15:29

1 Answers1

1

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • can there be a problem on my code if i continue my code that i said earlier without bind params sir? just asking out of curiosity cuz it seems it works properly without the bind params sir – Nao201431688 Dec 10 '19 at 15:47
  • Yes (possibly in rare cases), but most importantly you are making messy code for completely no reason. Stick with simple recommended solutions – Dharman Dec 10 '19 at 15:47
  • kindly look sir i edited the dboperation.php code sir the one that seems to be working – Nao201431688 Dec 10 '19 at 15:53
  • I see, and I am telling you that you should use bind_param. Don't use `mysqli_real_escape_string`. It makes your code vulnerable to SQL injection and really messy. Stick with bind_param. – Dharman Dec 10 '19 at 15:54
  • take a look again sir i still retained some of the codes and then followed youre advice sir, is the format okay now sir? tyvm for answering my questions! – Nao201431688 Dec 10 '19 at 16:16
  • wait ahaha sorry sir i thought i am doing it right sir its just when i tried your code sir it only insert 1 row to my database sir then i thought maybe i can combine the previous code to yours sir, – Nao201431688 Dec 10 '19 at 16:34
  • im redoing it again sir based on your code and it always send 1 row to the database sir – Nao201431688 Dec 10 '19 at 16:37
  • Can you show me how you are doing it based on my code? – Dharman Dec 10 '19 at 16:38
  • exactly the same as yours sir, i updated the code sir – Nao201431688 Dec 10 '19 at 16:44
  • That is not exactly the same as I did. I didn't put `return` inside of the loop. You return from the function after the first row is inserted. Move the return to the end of the function (without execute) or simply do not put return there at all. The code in my answer is a fully working example. It doesn't include error checking, but then again your code didn't really have it either. – Dharman Dec 10 '19 at 16:45
  • ah yes your right sir i just need to remove the return sir tyvm! , how do i make it work with the return sir? just like what i put in my code sir since i call the php code on cartData.php sir on android – Nao201431688 Dec 10 '19 at 16:56
  • Why do you need that return? It doesn't seem that useful at all. – Dharman Dec 10 '19 at 16:56
  • its just shows me if its a success or not hahahaha anyway i think its all good now tyvm for the help sir! – Nao201431688 Dec 10 '19 at 16:58