【问题标题】:Deleting single MySQL row with HTML and Node.js使用 HTML 和 Node.js 删除单个 MySQL 行
【发布时间】:2022-01-10 09:25:07
【问题描述】:

我正在尝试实现一种从表中删除所选行的方法。每行末尾都有一个Delete 链接,单击该链接将删除该行。当我运行它并单击Delete 链接时,它什么也不做。我没有收到任何错误,控制台显示0 row(s) updated 并且该行仍然存在。不知道我错过了什么。

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>

【问题讨论】:

  • 您期望 ID 来自参数和正文。 app.get('/delete', function(){})。休息一样。

标签: javascript html mysql sql node.js


【解决方案1】:

您将 id 作为路由 parameter 传递,而不是作为身体的一部分。 所以你应该使用 params 属性来访问它。

 var id = req.params.id;

试试看

【讨论】:

  • 另一方面,id 不会传递给 ejs 文件中的参数。因此,id 将是未定义的。
  • 感谢您的帮助!我将变量更改为您的解决方案,但现在它显示“无法获取/删除/20”。我不确定如何纠正这个问题?
  • 你是改了路线还是哪里有错字?未指定路由时会发生无法 GET。我发布的代码应该不会影响它。
  • Here 是它在任何小提琴上工作的一个例子。您可以看到 id 作为参数正确传递。
  • 我不得不完全退出我的虚拟机并重新连接,它现在突然可以工作了。非常感谢那是我的错
猜你喜欢
  • 1970-01-01
  • 2012-10-10
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 2018-06-04
相关资源
最近更新 更多