在不同的表Mysq,Node.js中插入多个信息

所以,我有三个表,用户,模块和一个中间表user_module,要在用户和模块之间进行内部联接,我必须访问完整的user_module

"SELECT user.uName,module.moduleName FROM user_module INNER JOIN user ON user.userID = user_module.userID_FK INNER JOIN module ON module.moduleID = user_module.moduleID_FK;",

我有一个表格,可以让我为用户插入信息,我想选择用户选择的模块。到目前为止,我一直在使用phpmyadmin手动为user_module表添加信息,其余的用户信息来自node.js代码

const parsed = bodyParser.urlencoded({ extended: false });
app.post("/",parsed,(req,res,next) => {
  console.log(req.body);
  connection.query(
    "INSERT INTO user(name,surname,gender,dateOfBirth,email,username,password) values('" +
      req.body.name1 +
      "','" +
      req.body.surname1 +
      "','" +
      req.body.gender +
      "','" +
      req.body.birtdate +
      "','" +
      req.body.email1 +
      "','" +
      req.body.username1 +
      "','" +
      req.body.password1 +
      "');",(err,row,field) => {
      if (!err) {
        res.redirect("/");
      } else {
        console.log(err);
      }
    }
  );
});

但是我如何从表单中获取信息,并将2个id放在中间表中?

<form action="/" method="post">
      <p>Name:</p>
      <input type="text" name="name1" /><br />
      <p>Surname:</p>
      <input type="text" name="surname1" /><br />
      <p>Gender:</p>
      <select name="gender">
        <option value="m">Male</option>
        <option value="f">female</option> </select
      ><br />
      <p>course:</p>
      <select name="module">
        <option value="1">Programming</option>
        <option value="2">webApp</option> </select
      ><br />
      <p>Date of Birth:</p>
      <input type="date" name="birtdate" placeholder="select Birth date" />
      <p>Email:</p>
      <input type="email" name="email1" />
      <p>username:</p>
      <input type="text" name="username1" />
      <p>Password:</p>
      <input type="password" name="password1" /> <br />
      <input type="submit" value="submit" />
    </form>
lmn1101 回答:在不同的表Mysq,Node.js中插入多个信息

这里的操作顺序非常重要:

1)您必须先保存用户,因为您需要具有其ID。 成功保存后,您需要获取其ID。有时,成功保存后,某些框架会提供已保存实体的ID,但您始终可以通过新的SQL查询手动获取它,以使用特定电子邮件获取用户ID。

SELECT id from users where email='email_of_the_user_you_just_saved"

2)在获得用户ID之后,并从前端收集了模块ID,然后只需将其插入到中间表user_module中即可。

INSERT INTO user_module (user_id,module_id) VALUES (users_id_you_got_from_step_1,module_id_you_got_from_frontend);
本文链接:https://www.f2er.com/3142006.html

大家都在问