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

When encountering an OR operator, Javascript will cease execution of the remaining conditions

This is a basic JavaScript form-validation I created. All the document.form.*.value references are present on my page, except for the document.form.dasdasdas.value ==''. In the code below, the purpose is to display an error if any of the forms a ...

Exploring the power of Bacon.js and RxJS in combination with Express.js and Mongoose.js

Currently, I have integrated Bacon.js into my server-side application using Express.JS (version 4.x). However, I am encountering an issue where the method does not respond at all. Can anyone help me figure out what might be causing this problem? var User ...

What is the reason for the error that is being caused by using arrow functions in my code

I'm currently working on a React application, but I keep running into errors that are causing issues. Here is the code snippet in question: import React from 'react'; import { Link } from 'react-router-dom'; const LINKS = [ { to ...

Using jQuery to select the third element from every group of six

I am attempting to select the 3rd .foo element out of every set of 6. To clarify, here is a brief example: 1 2 3 (this) 4 5 6 1 2 3 (this) 4 5 6 and so on... So far, I have only managed to target every 3rd element, which is not exactly what I need beca ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

HTML form submission with a grid of multiple choice options

I have created my own multiple choice grid: <div style="overflow-x:auto;"> <table class="w-100"> <tr> <td class="border"></td> <td class="border">Yes</td> <td class="border">No</ ...

Creating a Sudoku game board using underscore templates

Currently, I am in the process of constructing a Sudoku board using underscores templating. However, I have hit a roadblock when it comes to tackling the mathematical aspects necessary for deriving the table structure. My approach involves utilizing a 1d ...

Having trouble getting the auto complete feature to work in AngularJS with jQuery

I have been attempting for the last 5 hours without any success... Below is the code snippet: Within View: <input type="text" ng-model="foo" auto-complete/>Foo = {{foo}} Inside the controller: myapp.directive('autoComplete', functi ...

Determine the number of posts in each category using ExpressJS and Mongoose for querying

I am brand new to the MERN stack and I recently attempted to write a query, but unfortunately I was unsuccessful. Despite searching extensively on Google, I couldn't find a solution. I have two tables - one for posts and the other for categories Tab ...

Sending information across React context

I've encountered a challenge when trying to transfer data from one context to another in React. The job data I receive from a SignalR connection needs to be passed to a specific job context, but I'm unsure of the best approach for achieving this. ...

The CloudWatch logs for a JavaScript Lambda function reveal that its handler is failing to load functions that are defined in external

Hello there, AWS Lambda (JavaScript/TypeScript) is here. I have developed a Lambda handler that performs certain functions when invoked. Let me walk you through the details: import { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' ...

What is React.js's approach to managing CSS files?

Currently, I am enrolled in Bootcamp at Scrimba where they utilize an online platform for teaching various courses. One of the topics covered is React and involves working with CSS files. When working on my local machine, I typically use the index.css file ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Using the <script> attribute within the <head> tag without the async or defer attributes

https://i.stack.imgur.com/cRFaR.pngCurious about Reddit's use of the async or defer attribute in the script tag. Are there situations where blocking the parser is necessary? ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads within the iFrame when clicked. I&a ...

Creating registration and login forms using an express server

Currently, I'm in the process of creating a basic website on my localhost that incorporates a signup form along with other essential HTML elements. The setup for the signup procedure went smoothly as planned. When a user completes the form and submits ...