skip to Main Content

My Code:

function checkLogIn() {
  var emailValue = document.getElementById("emails").value;
  var usernameValue = document.getElementById("username").value;
  var passwordValue = document.getElementById("password").value;

  knex("users").select("id").where({
    email: emailValue,
    username: usernameValue,
    password: passwordValue,
   });
}

It should takes values from HTML and compare HTML values with MySQL DB values.
I know that the code is not properly correct but since I didn’t find anything about it, I was trying to test it a little bit. Does someone have any answer?

2

Answers


  1. The knex function will return a promise and when that promise is fulfilled, either an empty array or an array of length 1.

    To check if a user exists with the email, username, and password value they entered, try:

    async function checkLogIn() {
      var email = document.getElementById("emails").value;
      var username = document.getElementById("username").value;
      var password = document.getElementById("password").value;
    
      var [user] = await knex("users").select("id").where({ email, username, password });
      return !!user
    }
    

    Note that you should never store a password directly, instead store the bcrypt of the password, preferably with a salt.

    Login or Signup to reply.
  2. I thought I would chime in with a modern version of an answer that doesn’t leak out variables anywhere and utilizes the best of Knex 🙂

    See the comments explaining the nuances of the code.

    async function checkLogIn() { // make sure to put async in front of your function so it supports await
      
      // best to use const here to scope it only to this function 
      const email = document.getElementById('emails').value;
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
    
      const user = await knex('users')
                          .select('id')
                          .where({ email, username, password })
                          .first();
      // note that I chained the .first() to the query so that you only get the first match. 
      // Likely, your email and/or username fields are unique so that there can only be one result anyways
    
      return !!user // this bit returns a boolean (true/false) in case the user exist.
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search