1

I am trying to implement a way to delete a chosen row from my table. There is a Delete link at the end of each row which when clicked is meant to delete that row. When I run it and click the Delete link it does nothing. I don't get any errors, the console says 0 row(s) updated and the row remains. Not sure what I'm missing.

app.get('/device-list', function (req, res) {
  // query database to get all the devices
  let sqlquery = 'SELECT * FROM devices';

  // execute sql query
  db.query(sqlquery, (err, result) => {
    if (err) {
      res.redirect('/');
    }
    res.render('device-list.html', { availableDevices: result });
  });
});

app.get('/delete/:id', function (req, res, next) {
  var sql = 'DELETE FROM devices WHERE id = ?';
  var id = req.body.id;

  db.query(sql, [id], function (err, result) {
    if (err) {
      throw err;
    }
    console.log(result.affectedRows + ' row(s) updated');
  });
  res.redirect('/device-list');
});
<table>
  <thead>
    <th>Name</th>
    <th>Type</th>
    <th>Room</th>
  </thead>
  <tbody>
    <% availableDevices.forEach(function(device){ %>
    <tr>
      <td><%=device.Name %></td>
      <td><%=device.Type %></td>
      <td><%=device.Room %></td>
      <td><a href="/edit/<%=device.id%>">Edit</a></td>
      <td><a href="/delete/<%=device.id%>">Delete</a></td>
    </tr>
    <% }) %>
  </tbody>
</table>
1
  • You are expecting an ID to come from both params and body. app.get('/delete', function(){}). Rest the same. Commented Jan 10, 2022 at 16:05

1 Answer 1

1

You are passing the id as a route parameter not as a part of a body. So you should access it using the params property.

 var id = req.params.id;

Give it a try

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

5 Comments

On the other hand, id is not passed to params in the ejs file. therefore, id will be undefined.
Thanks for the help! I changed the variable to your solution but now it shows 'Cannot GET /delete/20'. I'm not sure how to correct this?
Did you change the route or is there a typo anywhere? Cannot GET happens when the route is not specified. The code I posted should not have affected it.
Here is an example of it working on any fiddle. You can see that the id is getting passed correctly as a param.
I had to completely exit my VM and reconnect and it suddenly works now. Thanks a lot that was my bad

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.