skip to Main Content

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%>" class="btn btn-danger btn-sm">Delete</a>

My table

I can delete one row, but I can’t delete more at once.

2

Answers


  1. Chosen as BEST ANSWER
          const urlencodedParser = express.urlencoded({ extended: false });   
    
       router.post("/groupDelete", urlencodedParser, function (request, res, next) {
          var groupIds = request.body.shouldDelete;
          const sql = `DELETE FROM users WHERE id IN (${groupIds.join(",")}) `;
          console.log(sql);
          db.query(sql, function (err, data) {
            if (err) {
              throw err;
            } else {
              res.redirect("/users/user-list");
            }
          });
        });
    
    
        <form action="/users/groupDelete" method="POST">
          <input
            type="checkbox"
            name="shouldDelete"
            id="34"
            value="34"
            for="row1"
          />
          <input
            type="checkbox"
            name="shouldDelete"
            id="36"
            value="36"
            for="row3"
          />
          <button type="submit">Send</button>
        </form>
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search