【问题标题】:How to query MySQL column against a posted variable?如何针对已发布的变量查询 MySQL 列?
【发布时间】:2022-01-20 21:09:46
【问题描述】:

我正在尝试查看连接的数据库是否有一封与用户发布的电子邮件相匹配的电子邮件:

app.post("/forgot_password", (req, res, next) => {

try {
const { emailId }  = req.body;
db.query("SELECT * FROM user WHERE email = ?", async (error, results) => {
if (error) {
  console.log(error);
}
if (emailId != results) {
  //Change to pop up saying incorrect email
  res.render("forgot_password")
  return
}
})

} catch (error) {
console.log(error)
}
})   

如何检查“email”列中的任何数据是否与此处发布的“emailId”常量匹配:

<form action="" method="POST">
    <label for="email">Email</label>
    <input type="email" name="emaild" id="email">
    <br>
    <input type="submit" value="submit">
</form>

【问题讨论】:

    标签: javascript mysql node.js


    【解决方案1】:

    你必须为查询提供变量

    const { emailId }  = req.body;
    db.query("SELECT * FROM user WHERE email = ?", [emailId], async (error, results) => {
    

    请注意,我在查询函数中添加了一个参数。它的签名是:

    db.query(sqlString, arrayOfParameters, callbackFuntion)
    

    这是文档的链接: https://github.com/mysqljs/mysql#performing-queries

    查询从数据库中返回一个行数组,其中电子邮件列与 emailId 的值匹配。我假设 emailId 是用户提供的实际电子邮件,例如myname@domain.com

    结果应该只有一行,因为我假设不同的用户不能拥有相同的电子邮件。

    所以要检查电子邮件是否匹配,只需验证行数是否为 1

    const { emailId }  = req.body;
    db.query("SELECT * FROM user WHERE email = ?", [emailId], async (error, results) => {
      if (error) {
        console.log(error);
        return // we want to exit the function
      } 
    
      // so you can see what the results are
      console.log(results) 
      if (results.length === 1) {  
        console.log('the user supplied an email that exists in our database')
      } else {
        console.log('no email found', emailId)
      } 
    })
    

    【讨论】:

    • 我明白了,我已将参数添加到查询中,但仍然无法将 emailId 与列结果匹配。我怀疑是因为“结果”给了我整个列而不是检查是否有任何行与 ID 匹配,我如何搜索每一行而不是整个列?
    • 感谢上述解决方案有效。虽然我之前尝试过,但我发现 html 中输入的“名称”有错字,因此找不到与电子邮件匹配的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2015-02-12
    • 2022-11-10
    • 1970-01-01
    • 2015-10-12
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多