Inserting multiple rows in MySql using JavaScript through a URL pathUnique: "

Hello there! I am currently attempting to send an array of objects to my MySql Database via an API endpoint.

Below is the code snippet from my API:

app.get("/orderdetails/add", (req, res) => {
  const {
    item__,
    Qty_Ordered,
    Unit_Price,
    Ext_Price
  } = req.query;
  const INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__, 
    Qty_Ordered, Unit_Price, Ext_Price) VALUES('${item__}', '${Qty_Ordered}', 
    '${Unit_Price}', '${Ext_Price}')`;
  connection1.query(INSERT_ORDERDETAILS_QUERY, (err, results) => {
    if (err) {
      return res.send(err);
    } else {
      return res.send("successfully added order details");
    }
  });
});

Furthermore, here is the function implemented in my Application:

addOrderDetails = _ => {
  const o = this.props.o;
  const summary = o.filter(function(obj) {
    return obj.Quantity >= 1;
  });
  var url = "";
  summary.forEach(function(e) {
    url +=
      "item__=" +
      e.ExternalID +
      "&Qty_Ordered=" +
      e.Quantity +
      "&Unit_Price=" +
      e.Price +
      "&Ext_Price=" +
      e.ExtPrice +
      "&";
  });
  url = url.trim("&");
  fetch(`http://localhost:4000/orderdetails/add?${url}`).catch(err =>
    console.error(err)
  );
};

Upon running addOrderDetails, I noticed that the generated statement sent to MySql looks like this:

INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price) 
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75')

This situation seems incorrect... Is there a method I can use to insert multiple rows into the mysql database within the same context?

The process works correctly when adding only one row...

Your assistance would be greatly appreciated!

Thank you,

Answer №1

If you need to insert multiple rows into a MySQL database, you can achieve this by using the following statement:

INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price)
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('C-2080,C-2081', '8,5', '18.75,18.75', '150,93.75'),
VALUES('B-2080,B-2081', '8,5', '18.75,18.75', '150,93.75');

To simplify this process, consider changing your API to a POST call and sending an array of data to it. Within your API, you can then generate the query described above.

You can use a basic for loop to construct such a query efficiently.

let summary = [1,2,3,4] // dummy data
let INSERT_ORDERDETAILS_QUERY = `INSERT INTO oe_details (item__, Qty_Ordered, Unit_Price, Ext_Price) VALUES`
summary.forEach(function(data, i) {
  INSERT_ORDERDETAILS_QUERY = `${INSERT_ORDERDETAILS_QUERY} (${data})`;
  INSERT_ORDERDETAILS_QUERY = (i !== summary.length - 1) ? `${INSERT_ORDERDETAILS_QUERY}, ` : `${INSERT_ORDERDETAILS_QUERY};`;
})

I hope this explanation is helpful to you!

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

Tips for selecting a specific input field in a ReactJS component with multiple inputs

I am currently developing a ReactJS application where I have implemented a component responsible for generating an HTML table. Within this component, I utilize Map to create rows using a child component. These rows contain multiple input fields that users ...

Is there a way to programmatically click on a link within the first [td] element based on the status of the last [td] element in the same [tr] using codeceptjs/javascript?

The anticipated outcome: Pick a random assignment from the table that has the status "Not start". Below is the table provided: <table id="table1"> <tbody> <tr class="odd1"> <td> < ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Provide details on the final parameters

After creating my discord.js bot, I had the idea to implement a translator feature. To achieve this, I need to extract the last argument from incoming messages. client.on("message", async (message, args) => { if (message.content.startsWith(` ...

Transforming sentence into a module function

Within my Node environment, I have updated my package.json file by adding "type": "module" to convert it into ES modules. The main server file now includes the following code: readdirSync("./routes").map((route) => app.use ...

Mongoose query for Model.find() is returning no results

Currently, I am working on querying all the data from a specific collection in my MongoDB database using Mongoose: Here is the request URL: http://localhost:3000/listdoc?model=Organization The code snippet I am using is as follows: exports.listDoc = fu ...

Tips for continuing code execution in an ajax success function following the completion of a nested ajax call within the success block

I am facing an issue with a function that utilizes $.ajax. In the success section of the function, I have three nested functions. The first one executes properly, but the second one contains another $.ajax call. While the internal $.ajax call works fine, t ...

Activate Bootstrap 5 dropdown exclusively when positioned above its parent element

I am facing an issue with a Bootstrap 5 dropdown menu placed within a div. When I click the icon, the dropdown appears but only those options that overlap the parent div can be hovered/clicked. In the provided screenshot, the 'Action' option fun ...

Sending a JSON array in an AJAX request results in receiving null values in an MVC application

I've been trying to send an array of JSON objects to my controller action, but it keeps showing up as null. Here's the JavaScript code I'm using: function UpdateSelected() { var items = {}; //Loop through grid / sub grids and crea ...

When attempting to add objects to an indexedDB object store, an InvalidStateError is encountered

I have defined IndexedDB and IDBTransaction dbVersion = 1; var db; var dbreq; var customerData = { ssn: "444", name: "Bill", age: 35, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bbbebe92b1bdbfa2b3bcabfcb1bdbf"& ...

Error message: Upon refreshing the page, the React Router is unable to read properties of

While developing a recipe application using the Edamam recipe API, everything was functioning smoothly until an issue arose when refreshing the Recipe Detail page. The error occurs specifically when trying to refresh the page with a URL like http://localho ...

Enabling communication between directives using controller API in AngularJS

Interaction Between Child and Parent Directives While the code below generally functions properly, there is an issue that arises when the template line in the parent directive (parentD) is uncommented: .directive('parentD', ['$window', ...

The logo image in the React application is having trouble rendering, showing a "Module Parse Failed" error

I am facing an issue while trying to render an image in my React component. The problem arises when I attempt to load and display my Logo within the component. A parse error is being thrown, and I am unsure of the reason for this error: Uncaught Error: Mo ...

MySQL Timeout Issue with NodeJS Connection, Not related to authentication issues

Everything runs smoothly with my NodeJS MySQL integrated database most of the time. However, during longer execution processes, I consistently encounter the same error. Error: connect ETIMEDOUT at Connection._handleConnectTimeout (/root/bot/node_module ...

Tips for sending a form using Angular 1.5.8 and Java Servlet via POST method

After reading various tutorials and online documentation, I'm still struggling to figure out how to pass parameters from a JSP form. Below is the JavaScript script I am using: var app = angular.module('myApp', []); app.controller('Form ...

Switching measurement unit to jQuery when retrieving image weight

After coming across a solution on this question, I am looking to determine the weight of an image from a file input. The solution I found displays the result in MiB (Mebibyte) unit. Is there a way to show the image weight using the same code, but in a diff ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

What is the best way to refresh the user feed following a post update?

My components include a UserFeed component and an EditForm component. After editing the form, I want to be redirected back to the UserFeed where the updated data (title and description of the post) should be displayed. The flow should go like this - start ...

Converting a json array into a map with the help of Underscore.js

My challenge involves parsing a JSON array into a map object, with the key being the state and the value being an array of objects that share the same state. An example JSON data set is provided below: { "totalRec": 10, "content": [ { "name" ...