Home > Software design >  msql query not returning data even though it exists
msql query not returning data even though it exists

Time:01-04

I am trying to make a login form. I send the data from frontend like seen here:

      const username = loginform.username.value.trim();
      const password = loginform.password.value.trim();
      console.log(username, password)

      Axios.post(apiUrlEndpont, {
        username: username,
        password: password,
      }).then((res) => {
        if(res.data.err){
          console.log(res.data.err)
        } else {
          console.log(res)
        }

      })

I get the username and password successfully. But the SQL query won't work for some reason which I don't recognize.

export default async function handler(req, res) {

const dbConnection = await mysql.createConnection({
    host: "localhost",
    database: "testapp",
    user: "root",
    password: "",
    socketPath: ""
})

if (req.method === 'POST') {
        const username = req.body.username
        const password = req.body.password
        console.log(username, password)

dbConnection.query(`SELECT password FROM accounts WHERE username = '${username}'`)
        .then((err, rows, fields) => {
            console.log("asd")
            if(rows.length!=0){

              var password_hash=rows[0]['password'];
              const verified = bcrypt.compareSync(password, password_hash);
              
              if(verified){

               res.send(rows[0])
                res.end()
              } else {

              res.send({err: "Invalid password"})
                res.end()
              }
          
            }else{
                res.send({err: "Invalid username password"})
                res.end()
            }
        })

}

}

rows will return undefined even though the username exists in the database.

I am a newbie with node and mysql so please be patient

CodePudding user response:

can you change your code like this and try.

sequelize.query(`SELECT password FROM accounts WHERE username = '${username}'`)
        .then(([rows]) => {
         console.log(rows); 
        ...
})
  • Related