I am new to Node.js and SQL programming and I encountered a problem where I don't know how to get, if the user already exists in the database. I tried to check if (selectUsername.length = username) and it didn't work. I also tried with the version from a previous post in stackoverflow
const selectUsername = conn.query("SELECT username FROM user WHERE username= "+ username, function (err, row){
if (row && row.length) {
console.log('Case row was found!');
} else {
console.log('No case row was found :( !', err);
}
})
Username is a variable where my username from form was inserted.
I always get the error Unknown column 'username' in 'where clause'
I have a register form and I want to check if a user already exists so there are no multiple users in the database, so that I can show an error if a user already exists.
Don't substitute a variable into the SQL, use a placeholder and a parameter array.
const selectUsername = conn.query("SELECT username FROM user WHERE username= ?", [username], function (err, row){
Related
I am having the following problem with node and mysql:
I have a function registerUser that takes the req.body with the user credentials and store them into a mysql db.
First of all I check that the email provided does not already exist. I have done this validation working with postgres in the following manner: if(user.rows.lenght!==0) return res.send("user already exist")
Then I pass to the next line of code that insrts the credentials into the db.
My problem is that using mysql, user.rows is undefined. I am having trouble extracting the data from the response which would allowme to perform some sort of validation.
My code is like this:
registerUser:async(req,res)=>{
const resolver=Resolver(res)
try {
//get data from req.body
const {userName, userEmail, userPassword}=req.body
//Check if user alreday exist on db by email
const user=db.query("SELECT * FROM users WHERE user_email=?",
[userEmail],(err,result)=>{
if(err) console.log(err)
else if(result.length!==0) return res.status(401).send('user already exist')
})
The callback function of the query does not stop the execution of the registeruser function. Also, the result comes with the user credentaials which is what I need, but I dont know how to extract it from the callback in order to use it in the scope of registerUser
I have been trying to setup my Nodejs MySQL database configuration. I found this passport.js config for MySQL on Github. The config works properly but there is a part that I do not understand.
var insertQuery = "INSERT INTO users ( email, password ) values ('" + email +"','"+ password +"')";
console.log(insertQuery);
connection.query(insertQuery,function(err,rows){
newUserMysql.id = rows.insertId;
return done(null, newUserMysql);
});
I am confused about the insertID field. The table I am using does not have a field called insertID. It does however have a field named ID. I tried changing that line to
newUserMysql.id = rows.Id;
bu doing so gives me:
Error: Failed to serialize user into session
Leaving it as it is gives me no error
Looks like insertID has nothing to do with the ID field of my table but I do not understand what it means
That probably represents LAST_INSERT_ID() which is the ID of the last row inserted.
The response of an INSERT is not "rows" but a result object, so maybe better named it'd be:
connection.query("...", function(err, result) {
newUserMysql.id = result.insertId;
return done(null, newUserMysql);
});
It's important to note that using Promises dramatically simplifies your code, and async/await can take that even further. This could be as simple as:
let result = await connection.query("...");
newUserMysql.id = result.insertId;
return newUserMysql;
Where that's inside an async function with a Promise-driven database library like Sequelize. You're not handling the potential errors in your first case. In the second you'll get exceptions which will wake you up when there's problems.
I am using Auth0 for a login service but I have a need to add a user to a database in MySQL every time an account is registered through Auth0.
They give this following script template but I am a newbie and need help debugging and understanding it. My specific questions are detailed as comments:
function create(user, callback) {
var connection = mysql({
host: 'localhost', //what should this be?
user: 'KNOWN/Understood',
password: 'KNOWN/Understood',
database: 'KNOWN/Understood'
});
connection.connect();
var query = "INSERT INTO users SET ?"; //what does this do?
bcrypt.hash(user.password, 10, function (err, hash) { //what does this do?
if (err) { return callback(err); }
var insert = {
password: hash,
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
});
}
Is there anything else I need to change for this script or understand or call in for it to work?
I often get the error missing username for Database connection with requires_username enabled and I'm unsure what this means.
I'm assuming you already went through this tutorial on custom databases so let's address your specific questions.
host: 'localhost' // What should this be?
This and the other properties of this object define the way to connect to your custom MySQL database. The database needs to be reached from within Auth0 servers so this needs to be a host name accessible from the Internet.
"INSERT INTO users SET ?"; // What does this do?
This defines an SQL insert command that uses ? as a placeholder for later substitution.
If you see where this query is later used, you will noticed it's invoked with an additional insert object parameter that will cause the above query to be expanded into something like:
INSERT INTO users SET email = 'user#example.com', password = 'asdf34ASws'
bcrypt.hash(user.password, 10, function (err, hash) // What does this do?
This hashes the user provided password so that it's not stored in plain text in the database.
If you chose to require a username in addition to email you need to address this in your custom scripts as I believe the default templates assume that only email will be used.
This means that when creating the user in your database you also need to store the username and in the script to verify a user you also need to return the username.
I am running a query which gives me confusing results. I have a node.js server which takes some user input from a form on the client side and uses socket.io to get the input on the server. here is the function which runs after receiving user input
databaseCheck(data);
function databaseCheck(userInput){
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '12.34.56.78',
user : 'user',
password : 'password',
database : 'db'
});
connection.connect();
var query = connection.query('SELECT * from `table` WHERE `email` = userInput', function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log("connection failure");
});
connection.end();
}
So when ever I use this code, it keeps printing "connection failure" to the screen. It doesn't happen when I replace userInput with the "example#email.com" so I'm guessing there is some problem with using the variable userInput in the query. Can someone tell me what is wrong with my code?
Not only do you need to pass the userInput by appending it to the string, you need to escape it so that the query recognizes it as a string:
connection.connect();
var query = 'SELECT * from `table` WHERE `email` = ' + JSON.stringify(userInput);
console.log(query);
connection.query(query, function(err, rows, fields) {
if (!err) console.log(rows[0].username);
else console.log(err.name, err.message);
});
connection.end();
It also helps to make the error message more informative by displaying the actual error instead of a generic message.
Lastly, put connection.end(); inside the callback. According to what you said, it appears to work like you had it but it's generally a bad idea to end a connection before an asynchronous process using the connection has called back.
Ignore my last comment, it appears I was wrong in this particular case. According to the repository documentation, it says:
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
Try this for testing and resolution. Printing to the log will let you see what you are putting in the query.
var querystring = "SELECT * from table WHERE email LIKE " +
userInput;
console.log(querystring);
var query = connection.query(querystring, function(err, rows, fields) {...
login: function (req, res) {
var username = req.param('username');
var password = req.param('password');
User.findOne({username: username}, function (err, user) {
if (err || !user) {
return res.status('401').send("User with username \"" + username + "\" not found. Are you registered?");
}
...
Gives me undefined for the user object and I always end up in the error statement. The username variable has the correct value. The method, where I create records, works (so my connection with the DB is alright), and when I look into the DB, the record is there, with all the correct data.
I also tried User.find().where({username: username}).exec(function (err, user) { with no success...
Any suggestions about where can I look into (debugging or smth) or what might be the cause of the problem?
Jonathan's comment to inspect err pointed me in the right direction. My User model was as follows:
attributes: {
// Relations
passports: {
model: 'Passport'
},
//... other attributes
and I also have the relation belongsTo declared in the Passport model. The err was giving Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'users.passports' in 'field list', and of course in my user table in the database I did not have the passports column.
Conclusion: I had unnecessary entity relation declaration in the User model. This was working fine with MongoDB, but apparently with MySQL things quite different.