How to return a value from a mysql SELECT query in node.js

纵然是瞬间 提交于 2019-11-30 07:35:37
Piyas De

Your two functions should be something like -

function fetchID(data, callback) {
        connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, rows[0].id_user);
        });
}

and then

var user_id;

fetchID(data, function(err, content) {
    if (err) {
        console.log(err);
        // Do something with your error...
    } else {
        user_id = content;
    }
});

Here in the callback function, the returned variable content will hold the value for user_id.

EDIT

I have not solved the exact problem as you had described above.

But in following example, I have shown that, the callback mechanism is working -

First (Table creation and insert some dummy data)-

use test;
create table users (id int(11) primary key,username varchar(100));
insert into users values(1, "John");
insert into users values(2, "Sham");

Now I have made your post method as get and tested in browser.

Following is the full class tested in my localhost -

var application_root = __dirname,
    express = require("express"),
    mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
  host : 'localhost',
  user : 'root',
  password : 'admin',
  database: "test"
});
app.get('/getuser', function(req, res) {
  //get data from the request
    var data = {
        username: req.query.username
    };
    function fetchID(data, callback) {
        connection.query('SELECT id FROM users WHERE username = ?',        
               data.username, function(err, rows) {
            if (err) {
                callback(err, null);
            } else 
                callback(null, rows[0].id);
        });
    }
    var user_id;
    fetchID(data, function(err, content) {
        if (err) {
        console.log(err);
        res.send(err);  
        // Do something with your error...
        } else {
        user_id = content;
        console.log(user_id);
        res.send("user id is -" + user_id);
        }
    });
})
app.listen(1212);

Now these requests will produce this output - http://127.0.0.1:1212/getuser?username=john => user id is -1 and http://127.0.0.1:1212/getuser?username=sham => user id is -2

Hope this code example will help you to understand the callback in node.js.

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!