Itzik984
Itzik984

Reputation: 16764

Retrieving data from database in node.js

If i have this table on dataBase.js file:

client.query(
'CREATE TEMPORARY TABLE IF NOT EXISTS '+USER+
'(username VARCHAR(255), '+
'password VARCHAR(255), '+
'name VARCHAR(255), '+
'picture VARCHAR(255), '+
'PRIMARY KEY(username))'
);

and lets say i want to check if i have a given user already in my dataBase,

how can i get the data after running the following query? :

function checkUser(username,password){
client.query('SELECT username, password FROM ' + USER + 'WHERE username=?', [username] , 'AND password=?', [password] 
function (err, results, fields) {
        if (err) {
            throw err;
        }
 });
}

if an error occurred, it will be handled but how can get the needed data?

any help will be much appreciated!

Upvotes: 1

Views: 3547

Answers (1)

Andrey Sidorov
Andrey Sidorov

Reputation: 25456

if there is no errors, you have your data in the results

function checkUser(username,password,haveResult) {
    client.query('SELECT username, password FROM ' + USER + 'WHERE username=? AND password=?', [username, password],  
    function (err, results, fields) {
        if (err) {
            // problems
            throw err;
        } else {
            // do something with data - it is in results array
            var checkResult = true; // here something depending on query result
            haveResult(checkResult); // continue via callback
        }
    });
}


// use it
checkUser('bar', 'baz', function(isGood) {
    console.log('user is' + (isGood? 'good' : 'bad') );
});

Upvotes: 2

Related Questions