SQL Query not Giving a Result - mysql

I am trying to login my user and i need to search whether the user exists in the db or not. My db is ClearDB using MySQL on Heroku. I am using node.js. This is my code:
if (req.body.isAdmin === 1) {
connection.query(
`SELECT * FROM admin WHERE username='${req.body.username}' AND password='${req.body.password}'`,
function (err, rows) {
if (!err) {
console.log(rows);
res.status(201).json({
success: true,
message: "Admin Logged In!",
});
} else {
res
.status(404)
.json({ success: false, message: "Admin Not Found!" });
}
}
);
} else {
connection.query(
`SELECT * FROM guard WHERE username='${req.body.username}' AND password='${req.body.password}'`,
function (err, rows) {
if (!err) {
console.log(rows);
res.status(201).json({
success: true,
message: "Guard Logged In!",
});
} else {
res
.status(404)
.json({ success: false, message: "Guard Not Found!" });
}
}
);
}
} catch (error) {
res.status(500);
throw new Error(error);
}
In the above code, i first check whether the user is an admin or not, then i execute the respective query. The db connects properly i.e., there is no issue with the db connection.
The issue is that there is no output for any of the queries i.e., rows variable is empty. Even if the data is false and doesn't match the data available, it doesn't give an error and also doesn't give an output. I have double-checked the connection and the query and they seem fine. I don't get where the issue is. Please help!

Related

User entries not updating in database

I am using postman to send a request and I see Success message but in the database, it's not updated at all.
PostMAN request
database Snap shot
update services object: from this file I have used a database query to insert data in the database and set callBack funtion
const pool = require('../../config/database')
module.exports = {
updateUser: (data, callBack) => {
pool.query(
`UPDATE users SET firstName=?,email=?,password=?,lastName=?,phoneNumber=?, sex=? WHERE id=?`, [
data.firstName,
data.email,
data.password,
data.lastName,
data.phoneNumber,
data.sex,
data.id
], (error, results, fields) => {
if (error) {
return callBack(error)
}
return callBack(null, results)
}
)
}
}
update user controller here I have added a controller to update the user details which receive the data from update user services.
const {
create,
getUserbyID,
getUsers,
updateUser,
deleteUser,
getUserByEmail
} = require('./userService')
const {genSaltSync, hashSync, compareSync} = require('bcrypt')
const { sign } = require('jsonwebtoken')
module.exports ={
updateUser: (req, res) => {
const body = req.body;
const salt = genSaltSync(10);
body.password = hashSync(body.password, salt);
updateUser(body, (err, results) => {
if (err) {
console.log(err)
return false;
} // added
console.log("this is the body: "+JSON.stringify(req.body))
console.log("this is the results: "+ JSON.stringify(results))
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
return res.json({
success: 1,
message: "Updated Sucessfully"
})
})
},
}
router.js
router.patch('/update',checkToken, updateUser)
ADDED console.log
this is the body: {"Id":15,"firstName":"joey","email":"joey.chandler357#gmail.com","password":"$2b$10$ZBnRppSKAfQ1TrzGvs/wqOrVx/shb6ESJ7emXnC7IlWRN3VUGgfK2","lastName":"chandler","phoneNumber":"9860316634","sex":"Male"}
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
I can see your console.log message
this is the results: {"fieldCount":0,"affectedRows":0,"insertId":0,"serverStatus":2,"warningCount":0,"message":"","protocol41":true,"changedRows":0}
Here you can notice affectedRows: 0 it means no row updated this happens when condition is not matched with any of the records. In postman you are passing "Id" I is in capital format but at the time of accessing this in service you are using "data.id" id is small latter so this is creating problem
we can handle this
instead of
if (!results) {
return res.json({
success:0,
message: "failed to update user"
})
}
use
if (!results.affectedRows) {
return res.json({
success:0,
message: "failed to update user"
})
}
this will be much better then previous check
I think you need to use an "insert" to add the db record. It's using an update... so it's looking for a pre-existing record.
Try two things:
wrap “users” in quotes on your update query. I’ve seen this w Postgres where some words are reserved in raw queries.
Examine the database response from your update. See what is console logged.

Check if a user exists node.js mysql

i have user mysql table with users how to get user exists.
i check user using select user from where access token = .
and check result in node.js server.
app.post("/checkStatusUser", function (request, responce) {
var accessTokenCheck = request.body.accessToken;
console.log(accessTokenCheck);
con.query(
"SELECT * FROM user_token_individual WHERE user_access_token = ?",
[accessTokenCheck],
function (err, res) {
if (err) {
responce.json({
STATUS_CODES: 404,
});
console.log(404);
responce.end();
} else {
if (!res.lenght) {
console.log(res);
responce.json({
STATUS_CODES: 200,
});
console.log(200);
responce.end();
}
console.log(404);
responce.end();
}
}
);
});
I don’t understand how to check if there is a user with such a token.
in res i have two log 200 and 404 because why i dont understand
I'd suggest using the response.status function to indicate status to the user, you can then use response.json to indicate the message. You could also use response.sendStatus if you just want to send text status, this would append a message to the response.
I'd suggest using a 500 status code in the case of an error, this indicates something we didn't expect, this is up to you of course!!
So something like this should work:
app.post("/checkStatusUser", function (request, responce) {
var accessTokenCheck = request.body.accessToken;
console.log(accessTokenCheck);
con.query(
"SELECT * FROM user_token_individual WHERE user_access_token = ?",
[accessTokenCheck],
function (err, res) {
if (err) {
console.error("An error occurred:", err.message);
responce.status(500).json({ status: 500, message: "An error occurred: " + err.message });
} else {
if (res.length) {
console.log( "User found successfully.");
responce.status(200).json({ status: 200, message: "User found successfully." });
} else {
console.log( "User not found.");
responce.status(404).send({ status: 404, message: "User not found." });
}
}
}
)
});

Error inserting into users table in Node.js

I got the Failed to load resource: the server responded with a status of 500 (Internal Server Error)
in the // Error inserting into users table section.
What causes this problem? Where should I check? My database has all the mandatory fields. I am using SQL db.
function registerUser(rBody) {
const connection = mysqlConnection
return new Promise((resolve, reject) => {
// First attempt to has user password, and continue on success
bcrypt.hash(rBody.password, 10, (err, hash) => {
if (err) {
// Error crypting password
resolve({
success: false,
error: 'Error hashing password'
})
} else {
// Build query & insert into users table
const valuesStr = `(null, "${rBody.email}", "${rBody.firstName}", "${rBody.lastName}", "${hash}", null, 2)`
const queryString = `INSERT INTO users values${valuesStr}`
connection.query(queryString, (err, resp) => {
if (err) {
// Error inserting into users table
resolve({
success: false,
error: err
})
} else {
// User succesfully created
resolve({
success: true,
message: 'User succesfully created',
id: resp.insertId
})
}
})
}
})
})
}
Edit your query to insert into the table does not seem to follow the standard syntaxis. Try
const queryString = `INSERT INTO users(name of your columns) VALUES(${valuesStr}`)

How to show user not found error using node.js and mysql

I am implementing registration API, in this registration, I have email as unique and I want to check if email exists or not in db if exists it has to show email already exists message else it has to register.everything works fine up to this.Now I want to check if an email does not exist in the database it has to show user not found the error but I am not able to display this message.
Here is my code
createUser: function(req, res, next) {
UserModel.getByEmail(req.body.email,function(err, user) {
if(err) {
res.json({ 'valid': false, 'message': err.message });
} else {
if(!user) {
res.json({ 'valid': false, 'message': 'User not exists'}); //this message is not showing
} else {
if(user[0].id) {
console.log('hi');
res.json({ 'valid': false, 'message': 'Email already exists'});//works only if i use user[0].id instead of user
} else {
UserModel.addUser(req, token, function(err, data) {
//console.log(data);
if (err) {
res.json({ 'valid': false, 'message': err.message });
} else {
console.log('Message sent: ' + info.response);
res.json({Error: info.response});
res.json({ 'valid': true, 'message': 'User added succesfully', req:req.body, data : data });
}
});
}
}
}
});},
In getByEmail method
getByEmail: function(email, rows){
var sql = "SELECT * FROM sbt_users WHERE email = ?";
var fields = [email];
return db.query(sql, fields, rows);}
if(!user) is not working.Can anyone explain how to show that message.
user is an array of records. If the array is empty, it's length will be 0.
So you can check if (user.length === 0)

nodejs- unable to return result to controller function

From my Model, I fetch some articles from a MySQL database for a user.
Model
var mysql = require('mysql');
var db = mysql.createPool({
host: 'localhost',
user: 'sampleUser',
password: '',
database: 'sampleDB'
});
fetchArticles: function (user, callback) {
var params = [user.userId];
var query = `SELECT * FROM articles WHERE userId = ? LOCK IN SHARE MODE`;
db.getConnection(function (err, connection) {
if (err) {
throw err;
}
connection.beginTransaction(function (err) {
if (err) {
throw err;
}
return connection.query(query, params, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
//console.log(result);
});
});
});
}
This is working and the function fetches the result needed. But it's not returning the result to the controller function (I am returning it but I'm not able to fetch it in the controller function. I guess, I did something wrong here).
When I did console.log(result) this is what I got.
[ RowDataPacket {
status: 'New',
article_code: 13362,
created_date: 2017-10-22T00:30:00.000Z,
type: 'ebook'} ]
My controller function looks like this:
var Articles = require('../models/Articles');
exports.getArticle = function (req, res) {
var articleId = req.body.articleId;
var article = {
userId: userId
};
Articles.fetchArticles(article, function (err, rows) {
if (err) {
res.json({ success: false, message: 'no data found' });
}
else {
res.json({ success: true, articles: rows });
}
});
};
Can anyone help me figure out what mistakes I made here?
I'm pretty new to nodejs. Thanks!
The simple answer is that you're not calling the callback function, anywhere.
Here's the adjusted code:
fetchArticles: function (user, callback) {
var params = [user.userId];
var query = `SELECT * FROM articles WHERE userId = ? LOCK IN SHARE MODE`;
db.getConnection(function (err, connection) {
if (err) {
// An error. Ensure `callback` gets called with the error argument.
return callback(err);
}
connection.beginTransaction(function (err) {
if (err) {
// An error. Ensure `callback` gets called with the error argument.
return callback(err);
}
return connection.query(query, params, function (err, result) {
if (err) {
// An error.
// Rollback
connection.rollback(function () {
// Once the rollback finished, ensure `callback` gets called
// with the error argument.
return callback(err);
});
} else {
// Query success. Call `callback` with results and `null` for error.
//console.log(result);
return callback(null, result);
}
});
});
});
}
There's no point in throwing errors inside the callbacks on the connection methods, since these functions are async.
Ensure you pass the error to the callback instead, and stop execution (using the return statement).
One more thing, without knowing the full requirements of this:
I'm not sure you need transactions for just fetching data from the database, without modifying it; so you can just do the query() and skip on using any beginTransaction(), rollback() and commit() calls.