I am hoping to receive guidance on how to pass a mySQL stored procedure Javascript form data to use as parameters in a query.
I have been searching for an answer on how to use mySQL stored procedures with javascript form data as parameters.
This is what I have thus far:
var first_name = req.body.firstName,
last_name= req.body.lastName,
email= req.body.email,
password= req.body.password,
gpa= req.body.gpa,
major = req.body.major,
classification= req.body.classification;
var query = connection.query("CALL new_student()", function (err, result) {
if (err) {
res.send(err);
}
res.json(result);
})
Here is the stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `new_student`(IN first_name VARCHAR(45),
IN last_name VARCHAR(45), IN email VARCHAR(45), IN password VARCHAR(45), IN gpa DECIMAL(3,2),
IN major INT(10), IN classification VARCHAR(45))
BEGIN
INSERT INTO users (first_name, last_name, email, password)
VALUES (first_name, last_name, email, password);
INSERT INTO student (user_id, gpa, major, classification)
VALUES (LAST_INSERT_ID(),gpa, major, classification);
END
My intention is to take the variables, or a Javascript object that encapsulates the variables, and pass them in through "new_student()."
I am aware this may seem trivial. I am in the process of learning how to use stored procedures with Javascript.
You need to provide arguments to the function. If you're using the node-mysql-native you can provide the parameters using syntax like a prepared statement.
var query = connection.query("CALL new_student(?, ?, ?, ?, ?, ?, ?)", [first_name, last_name, email, password, gpa, major, classification],
function (err, result) {
if (err) {
res.send(err);
}
res.json(result);
})
For more information about this, see Preventing SQL injection in Node.js
Related
I'm a beginner in general and trying to use MySQL with nodeJS to be able to integrate projects in WordPress.
app.post('/users/add', (req, res) => {
id = req.body.id, firstname = req.body.firstname, surname =
req.body.surname
let sql = "INSERT INTO `users_tbl` VALUES (id, firstname, surname)";
db.query(sql, [id, firstname, surname],
(err, rows, fields) => {
if(!err)
res.send("User successfully added");
else
console.log(err);
});
})
With the given code I can add through Postman an entry, but an empty one.
I already tried to assign my values to the keys after VALUES, but maybe my syntax was wrong
Assuming you are using this module.
db.query(sql, [id, firstname, surname]
Here you are passing variables into your query for them to replace placeholder values.
let sql = "INSERT INTO `users_tbl` VALUES (id, firstname, surname)";
But here you have just put column names instead of placeholder markers.
Change that to:
let sql = "INSERT INTO `users_tbl` VALUES (?, ?, ?)";
Aside: You should probably have the id field be an auto-increment field and not a user-submitted value.
app.post('/users/add', (req, res) => {
id = req.body.id,
firstname = req.body.firstname,
surname = req.body.surname
let sql = "INSERT INTO `users_tbl` (id, firstname, surname) VALUES
(?,?,?)";
db.query(sql, [id, firstname, surname], (err, rows, fields) => {
if(!err)
res.send("User successfully added");
else
console.log(err);
});
});
Try this code just replace your values with ? and run postman again.
Add a breakpoint or use console.log to check if you are actually getting the body fields in req.body.
Try setting 'Content-Type' as application/json in headers while sending the request through postman and send raw json in body.
I want to encypt a password using BCrypt and then pass it to another function to store it in DB. The problem is that I can't pass it successfuly. I receive an error: "ReferenceError: hashedPass is not defined" on write-to-db.js:18
This part of code encrypts and has to send the hash to "write.registerUser()"
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser(function(data, fName, lName, email, role, date, hashedPass){
return();
});
});
});
That is write-to-db.js where I try to save to DB but fail:
registerUser(Callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+fName+"', '"+lName+"', '"+email+"', '"+role+"', '"+date+"', '"+1+"', '"+hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
Callback(result);
});
}
Any ideas?
change your registerUser function to:
registerUser(params, callback) {
var sql = "INSERT INTO users_data (first_name, last_name, email, role, registration_date, active, password) VALUES ('"+params.fName+"', '"+params.lName+"', '"+params.email+"', '"+params.role+"', '"+params.date+"', '"+1+"', '"+params.hashedPass+"')";
con.query(sql, function (err, result) {
if (err) throw err;
callback(result);
});
}
and change your hash generating code to:
bcrypt.genSalt(saltRounds, function(err, salt){
bcrypt.hash(query.password, salt, function(err, hashedPass){
console.log(hashedPass); //I get the hash printed here with no problems
write.registerUser({
data,
fName,
lName,
email,
role,
date,
hashedPass
}, function(results){
console.log(results)
return();
});
});
});
WARNING: this SQL query is vulnerable to SQL INJECTION. You would be wise to use prepared statements or an ORM.
This is my current javascript.
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'codify',
port: '8889'
})
connection.connect();
//var querydata = +"'"+data.RegUsername + "','"+data.RegPassword+"'"
connection.query("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES ?", data.RegUsername,+","+ data.Regpassword , function(err,rows,fields){
if (err) throw err;
})
});*/
This query causes an error, what am I doing wrong?
What you're doing wrong is that you're trying to concatenate your two values into a single string and have that string substituted into your single ?. If you're using a single ?, you need to pass in an object where the object's parameters are the same as the database field names.
I'd do it like this:
let payload = {
UsernameDB: data.RegUsername,
PasswordDB: data.Regpassword
};
connection.query("INSERT INTO Codify SET ?", payload, function(err, rows) {
});
You can also do it like this with an array instead of an object:
let sql = "INSERT INTO Codify (UsernameDB, PasswordDB) VALUES (?, ?)";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {
});
or like this:
let sql = "INSERT INTO Codify SET UsernameDB = ?, PasswordDB = ?";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {
});
But I find using a single ? along with an object is more readable.
placeholder ( ? character) will escape your querydata for avoid sql-injection. cause you don't use combined string for query. use placeholders to each inserted value. like
("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES (?,?)", [data.RegUsername,data.Regpassword] , function () )
check nodejs mysql driver document here
I'm working on an EC2 server and I need to insert some data into a mySql table from server-side.
I have verified that the information in the request body is accurate via logging their values to the console i.e. console.log(req.body.name). I also know that my table exists.
My connection pool is defined at the top of the page:
var pool = mysql.createPool({
host: 'localhost',
user:'student',
password: 'default',
database: 'workouts'
});
My insert inside of a POST function is:
pool.query("INSERT INTO workouts(`name`, `reps`, `weight`, `date`, `lbs`) VALUES (?, ?, ?, ?, ?)", [req.body.name, req.body.reps, req.body.weight, req.body.date, req.body.lbs],
function(err, result){
if(err){
console.log(err);
return;
}
});
});
My table was created using professor-supplied code:
app.get('/reset-table',function(req,res,next){
var context = {};
pool.query("DROP TABLE IF EXISTS workouts", function(err){ //replace your connection pool with the your variable containing the connection pool
var createString = "CREATE TABLE workouts("+
"id INT PRIMARY KEY AUTO_INCREMENT,"+
"name VARCHAR(255) NOT NULL,"+
"reps INT,"+
"weight INT,"+
"date DATE,"+
"lbs BOOLEAN)";
pool.query(createString, function(err){
context.results = "Table reset";
res.render('home',context);
})
});
});
var Database = (function(host, username, password, database) {
var connection = mysql.createConnection({
host: host,
user: username,
password: password,
database: database
});
return {
//all my functions
};
}());
I am trying to make a Database singleton in node to communicate with my database.
But how to I pass the arguments, (host, username, password, database) into it when I call it?
I cant do:
var db = new Database(HOST, USERNAME, PASSWORD, DATABASE);
since database is a singleton...
Also, how do I make a constructor inside Database, and how do I pass arguments into it??
The () on the final line is the list of arguments being passed to the function, and it is currently empty. Simply put your arguments there:
var Database = (function(host, username, password, database) {
var connection = mysql.createConnection({
host: host,
user: username,
password: password,
database: database
});
return {
//all my functions
};
}(HOST, USERNAME, PASSWORD, DATABASE));