Wednesday, May 29, 2019

Using MySQL stored procedures with Javascript objects



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.


Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...