Node-mysql insert query with two values? - javascript

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

Related

POST data into MySQL with NodeJS and Postman

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.

How come I'm getting a syntax error in my SQL code?

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.

node js: alert on database update

I'm trying to make something like console.log('Dear user, there was updates'). I made basic console.log for now which is not what I'm looking for because I want from node to check if there was some update on database, not updating in function.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
con.connect(function(err) {
if (err) throw err;
//Update the address field:
var sql = "UPDATE users SET name = 'lol2' WHERE name = 'lol'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
edit: alert to console.log
Alert wont work in Node.js Instead sent a response back to client side with the total affected of results. And based results, show alert with the count received.
eg.
return res.status(200).return(result.affectedRows);
and in client side
if(datareceived > 0){
alert(`Dear user, there was ${datareceived} price updates moment ago`)
}else{ // your other logic }

Insert Failing Node.js mysql

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);
})
});
});

node js Insert into mysql variable not work

I am using MySql with node.js
i have this query and it works:
connection.query('insert into username (name) values ("msg")', function(err, rows, fields) {
if(!err) {
} });
it inserts the string "msg", not the value of the variable msg, but when I want to insert the variable this does not work:
connection.query('insert into username (name) values '+ msg, function(err, rows, fields) {
if(!err) {
} });
for example:
var msg = "hello world!";
You are missing the parenthesis and the quotes that make a valid insert statement in the second case. You are building a sql statement that looks like this:
'insert into username (name) values hello world'
which is malformed. Use the util module to make your string formatting easier:
var util - require('util');
var mySql = util.format('insert into username (name) values ("%s")', 'hello world');
connection.query(mySql, function(err, rows, fields) {
if(!err) {
} });
try this code
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'pass',
database: 'db_name'
});
connection.query(`INSERT INTO user_table (name, mail, pass) VALUES ('${user_name}', '${user_name}', '${user_name}');`, function (err, result, fields) {
if (err) throw err;
});

Categories