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.
Related
I'm getting an error on the line that says
const INSERT_PRODUCTS_QUERY = 'INSERT INTO products(name, price) VALUES('${name}',${price})';
I know the error emanates from the single quotes in '${name}' but I also tried removing the single quotes in an attempt to get rid of this error and still get an error that says:
{
"code": "ER_PARSE_ERROR",
"errno": 1064,
"sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{name}, ${price})' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "INSERT INTO products(name, price) VALUES(${name}, ${price})"
}
Here's my code:
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const app = express();
const SELECT_ALL_PRODUCTS_QUERY = 'SELECT * FROM products';
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'react_sql'
});
connection.connect(err => {
if(err) {
return err;
}
});
app.use(cors());
app.get('/', (req, res) => {
res.send('go to /products to see products')
});
app.get('/products/add', (req, res) => {
const { name, price } = req.query;
const INSERT_PRODUCTS_QUERY = 'INSERT INTO products(name, price) VALUES('${name}',${price})';
connection.query(INSERT_PRODUCTS_QUERY, (err, results) => {
if(err) {
return res.send(err);
} else {
return res.send('successfully added products');
}
});
})
app.get('/products', (req, res) => {
connection.query(SELECT_ALL_PRODUCTS_QUERY, (err, results) => {
if(err) {
return res.send(err)
} else {
return res.json({
data: results
})
}
});
});
app.listen(4000, () => {
console.log("listening port 4000");
});
I don't know so much about SQL and its queries, so for this subject (strings, security, etc) listen to other people.
As you can see in the comments this opens the code to SQL Injections, better avoid to using it.
Thanks, #Keith.
But if you want to use variables in your strings either you need to combine different string pieces or you should use template literals.
PS: If you still really, really want to use template literals, you can check this node package which is sql-template-strings for NodeJS.
Notice the backticks: ``
const name = "foo";
const price = 100;
const INSERT_PRODUCTS_QUERY = `INSERT INTO products(name, price) VALUES('${name}',${price})`;
console.log( INSERT_PRODUCTS_QUERY );
SQL parameters in MySQL are not only a convenient way of passing parameters to query's, there also a must if you don't want to open your site to SQL Injection problems.
The changes you need to make are very minimal..
First change your query to ->
const INSERT_PRODUCTS_QUERY =
'INSERT INTO products(name, price) VALUES(?, ?)'
And when you use this query pass the parameters as the second parameter.
connection.query(SELECT_ALL_PRODUCTS_QUERY,
[name, price],
(err, results) => {
Template literals are not surrounded by simple quotes but by back-ticks "`"
It should become :
const INSERT_PRODUCTS_QUERY = `INSERT INTO products(name, price) VALUES('${name}',${price})`
You are not providing literals correctly, modify your query as following, this is PHP representation you can change accordingly.
INSERT INTO products(name, price) VALUES('".${name}."','".${price}."');
Single quote for literal value is ambiguous with language single quote, which breaks query syntax.
This is not best way to achieve this, as it opens your query to SQL Injection.
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 having trouble inserting data into a MySQL database. Select queries work fine, so I'm assuming that it's something stupid that I've missed, either in the Express code, or, in my HTML. The page I'm running the query from is located at localhost:8080/add, and I'm trying to INSERT INTO. Here's my code:
Javascript
app.get('/add', function(req, res) {
res.sendFile(path.join(__dirname + '/Views/add.htm'));
});
app.post('/add', function(req, res) {
var fName = req.body.fName;
var email = req.body.email;
var id = req.body.id;
var post = {id: id, user: fName, email: email};
console.log(post);//This holds the correct data
connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log('Was not able to add information to database.');
}
});
});
My HTML is simply a submit button and 3 input fields, within in a POST method form. Again, I can connect to the database and read from it with a select query, I just cannot insert into it.
Look at the documentation here https://github.com/mysqljs/mysql#escaping-query-values.
connection.query('INSERT INTO posts SET ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log(result);
console.log('Was not able to add information to database.');
}
});
Valid mysql statement is SET instead of Values.
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