Home > database >  how can i pass an array of parameters to route?
how can i pass an array of parameters to route?

Time:01-21

I want to delete some rows from mySql db using checkboxes from my ejs view to routes with node.js and react app. I can delete one row, but how can i pass and array of parameters?

this is my router delete-func

router.get("/delete/:id", function (request, res, next) {
  var id = request.params.id;
  const sql = `DELETE FROM users WHERE id = "${id}" `;

this is "delete button html code" with id for deleting one row from ejs file

<a href="/users/delete/<%=data.id%>" >Delete</a>

my table

I can delete one row but i cant delete more at once

CodePudding user response:

First of all, you should use DELETE instead of GET method to delete single row in your router.

You can use POST method to send an array of inputs to the server. So just need put a checkbox for each rows which name is "shouldDelete[]" or another name you like it.

It's important that using the brackets to send an array of inputs to the server. And then you should use a <form> to send your POST request.

Client:

<form action="/groupDelete" method="POST">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row1">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row2">
    <input type="checkbox" name="shouldDelete[]" value="ROW_ID_HERE" for="row3">
    <button type="submit">Send</button>
</form>

Server:

router.post("/groupDelete", function (request, res, next) {
  var groupIds = request.body.shouldDelete;
  const sql = `DELETE FROM users WHERE id IN ("${groupIds.join(',')}") `;

Notice: Observe safety precautions when querying the database.

CodePudding user response:

//solo del with id
router.get("/delete/:id", function (request, res, next) {
  var id = request.params.id;
  const sql = `DELETE FROM users WHERE id = "${id}" `;
  db.query(sql, function (err, data) {
    if (err) {
      throw err;
    } else {
      res.redirect("/users/user-list");
    }
  });
});

//group del
router.delete("/groupDelete", function (request, res, next) {
  var groupIds = request.body.shouldDelete;
  const sql = `DELETE FROM users WHERE id IN ("${groupIds.join(",")}") `;
  db.query(sql, function (err, data) {
    if (err) {
      throw err;
    } else {
      res.redirect("/users/user-list");
    }
  });
});

//client group
<form action="/users/groupDelete" method="POST">
  <input type="checkbox" name="shouldDelete[28]" id="27" for="row1" />
  <input type="checkbox" name="shouldDelete[29]" id="28" for="row2" />
  <input type="checkbox" name="shouldDelete[30]" id="29" for="row3" />
  <button type="submit">Send</button>
</form>

//client solo
<a href="/users/delete/28" >Delete</a>
  • Related