0

I have an invoice app where you can add many products to the same invoice (bill) in mySQL i have a products table where i want to add every single product i have added in the invoice. i have managed to save all the products inside an array.

Array [
  Object {
    "amt": "1",
    "desc": "Item1",
    "index": 0,
    "qty": "1",
  },
  Object {
    "amt": "2",
    "desc": "Item2",
    "index": 1,
    "qty": "2",
  },
  Object {
    "amt": "3",
    "desc": "Item3",
    "index": 2,
    "qty": "3",
  },
  Object {
    "amt": "4",
    "desc": "Item4",
    "index": 3,
    "qty": "4",
  },
]

on button click i want to send an api that inserts the data inside the table in mySQL.

 app.post("/addproducts", (req, res) => {
      let product= req.body;
      var sql =
        "INSERT INTO products (amt, desc, qty, invoiceId) VALUES(?, ?, ?, ?);";
      mysqlConnection.query(
        sql,
        [
          product.invoiceId,
          product.amt,
          product.desc,
          product.qty,
        ],
        (err, rows, fields) => {
          if (!err) {
            res.send(rows);
            });
          } else {
            res.send(err);
          }
        }
      );
    });

how can i fix my api to go through the array one by one and insert all the products inside the table

PS: invoice id is the foreign key inside the product table (don't mind it)

axios
      .post("http://192.168.0.117:3000/addInvoice", {
        address: address,
        invoiceId: invoiceId,
        amt: invoicenumber,
        desc: desc,
        qty: qty,
      })
      .then((response) => {
        alert("Invoice sent to customer!");
      })
      .catch((error) => console.log("error", error));
  };

this is the post api from front-end

How can i map through the data array (that i showed at the beginning) and send the objects one by one?

1
  • Well a loop of some sort would seem a likely start place Commented Sep 20, 2020 at 13:56

1 Answer 1

1

Bulk inserts are possible by using nested array.

In your case data should look like :

var sql =
    "INSERT INTO products (amt, desc, qty, invoiceId) VALUES(?, ?, ?, ?);";

let values = [
  ['1', 'Item1', '0', '1'],
  ['2', 'Item2', '1', '2'],
  ...
]

mysqlConnection.query(sql, values, ...)

(Care about field order)

Sign up to request clarification or add additional context in comments.

3 Comments

yes but how can i send the data from front-end to back end
can you help me with it?
This edit is adding another non related question, you should add it in another thread since it doesn't have any relation with inserting multiples records to MySQL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.