Tips for Effectively Adding Deciphered JSON Data into a Mysql Database

I have been struggling to figure out how to get my php code working with my database by searching online, but I'm having trouble understanding it all! That's why I decided to reach out and ask for help or guidance on this issue. Any assistance would be greatly appreciated!

Question: How can I insert JSON formatted data into a 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: Here is the array result 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 am aware that my php code in Dboperation.php may have some mistakes. I saw a video suggesting that I need to decode the array coming from Android first and then use a foreach loop with an Insert inside. However, I'm confused about how to properly use bind params on the decoded array. Do I really need to use them, considering that I should base it on the parameters used in the public function like "public function insertIndividualCart($cartarray){}"? As a beginner, I'm finding it challenging to grasp everything, so any help is truly appreciated!

Answer №1

This response is intended to guide you in the right direction without providing a complete solution. The key point is that you need to run the query within 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) {
        // Since there are 3 placeholders in the SQL statement, make sure to bind 3 variables
        $stmt->bind_param('sss', $row['productname'], $row['quantity'], $row['totalprice']);
        $stmt->execute();
    }

    return true;
}

As you can see, by preparing the query before entering the loop and then binding values inside the loop for execution, the code becomes more concise and efficient.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

Create separate arrays for the names and values when returning JSON

Suppose I have a JSON object like this: { "ID": 100, "Name": "Sharon", "Classes":{ "Mathematics": 4, "English": 85, "Chemistry": 70, "Physics": 4, "Biology" ...

Is this filter vulnerable to an XSS attack?

function sanitizeInput($input){ $index=0; return str_replace("<","&lt;",str_replace(">","&gt;",str_replace("&","&amp;",$input,$index),$index),$index); } Would this method be effective in preventing XSS attacks? Just my person ...

Social media filtering policy reaching maximum limit error following enhanced quota allocation

Recently, I encountered a situation where my SNS subscription had a filter policy containing 150 values. Aware of the limit on the value count, I promptly requested AWS to increase it. However, even after receiving an extended policy limit, I still encount ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Having trouble trying to update information using Sequelize and MySQL

I am in the process of developing an application that involves updating posts from the past. A dedicated page has been created for this purpose along with a corresponding route. app.post("/posts/:id/update", function(req, res){ Post.findAll({ ...

Using CakePHP, instantiate a new object and call the controller class from the index.php file located in the webroot directory

Struggling to reach the CustomersController class from index.php within the webroot folder in cakephp 3. After attempting to use the code below, an error message indicates that the class cannot be found. require dirname(__DIR__) . '/src/Controller/Cu ...

What is the process for transforming a self-iterating ArrayList into JSON with the help of Jackson

I need to transform a List of data into the JSON structure shown below. I have retrieved the data from MySQL into an ArrayList and defined the EducationDTO POJO class. { "id": "1", "name": "EDUCATION", "data": "", "children": [ { "id": "1.1", ...

Passing data from a card component to a tab component in ReactJS

Just starting out with react and facing an issue. I want to transfer props from the child component to the parent component tabs that include favorite tabs. My plan was to pass the values through the handleClickOpen method where I click the favorites icon. ...

Looking for assistance with transferring a JavaScript array to my PHP script

Is there an easier way to transfer a JavaScript array to a PHP file? I've seen examples of using AJAX for this task, but I'm wondering if there's a simpler method. Below is a snippet of the code I'm working with: <html> <hea ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

Parsing JSON inside a function in PHP involves extracting data from a JSON string and

I found something like this in a *.txt file. function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...}); This is how I am accessing the information from the file: $source = 'FILE_NAME.txt'; $json = json_decode(file_get_content ...

Looking to Connect 3 Tables Using Varying Columns

product_to_category p2c has 2 columns: category_id product_id There may be multiple entries for each product, so we need to use MAX (category_id). category_to_google c2g has 2 columns: category_id google_id google_category gc has 2 columns: google_id ...

"Resolving the problem of converting JSON to a C# class with integer class name

Received a JSON response with the following structure: { "serp": { "1": { "href": "href1.com", "url": "url1.com" }, "2": { "href": "href2.com", "url": "url2.com" ...

Transferring information back and forth from GWT to PHP

As someone who is new to both GWT and PHP, I have been struggling to understand how to efficiently exchange data between the frontend and backend. While I found success following tutorials that suggested using the RequestBuilder class for getting data from ...

The MySQL Query Maker

To fetch data from a database for only one row and then generate separate pieces of information, use the following code: <?php session_start(); ob_start(); error_reporting(E_ERROR | E_WARNING | E_PARSE); ini_set("display_errors", 1); set_time_limit(1 ...

Exploring Paths in a JSON Structure using Scala and a List

When working with Play Scala, we can navigate through properties in an object using the \ method: val name = (json \ "user" \ "name") If our path is defined in a list, how can we navigate to the node? val path = List("user","name") val n ...

Leveraging the power of jQuery's $.when and $.then methods for efficiently managing multiple AJAX requests that do not

My goal is to utilize jQuery to retrieve data from both an XML and JSON feed, and then only log the data when both requests are successful. When I comment out getRoomFeed() within the $.when, it returns the correct responseText object for the XML. However ...

Top solution for maintaining smooth navigation across web pages

As I dive into the world of web development, I find myself intrigued by the idea of reusing navigation and banners across multiple web pages. However, despite my research efforts, I have yet to come across a definitive answer. My objective is simple: The ...

What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data: var data = [ { "name": "wiredep", "version": "4.0.0", "link": "https://github.com/taptapship/wiredep", "lice ...