3

Hi the code below loads a single field from a mysql database, but when it gets to the point result[0].IdUtente the error below is generated. How do I solve it?

ERROR:

 throw err; // Rethrow non-MySQL errors
        ^

TypeError: Cannot read property 'IdUtente' of undefined

CODE:

var query = "SELECT IdUtente FROM Utente WHERE Username = " + sql.escape(Username) + " and Password=MD5(" + sql.escape(Password) + ") and Tipo!='Risorsa' ";
var ret=DbConfig.query(query, function (err, result) {
    if (err) {
        console.log("Errore login: " + err);
    }
    else {
        console.log(result[0].IdUtente);
        IdUtente = result[0].IdUtente;

    }

});
1
  • I was getting the same error. Realized that it was due to incorrect SQL syntax. Make sure that you are writing the correct SQL as well. Commented Apr 13, 2021 at 23:27

1 Answer 1

4

This error occur when the query pulls an empty result. You must first check the length of result with result.length property, only if the result is greater than 0 you must use index the result. Please check the code below.

var query = "SELECT IdUtente FROM Utente WHERE Username = " + sql.escape(Username) + " and Password=MD5(" + sql.escape(Password) + ") and Tipo!='Risorsa' ";
var ret=DbConfig.query(query, function (err, result) {
    if (err) {
        console.log("Errore login: " + err);
    }
    else {
        //check to see if the result is empty
        if(result.length > 0){
            console.log(result[0].IdUtente);
            IdUtente = result[0].IdUtente;
       }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.