How do you update two tables without joining in Node.js? - mysql

How do you update two MySQL tables with a single click of the retire button? I have created a table where you can edit based on the serial number of agent shown below. By clicking the retire button, it should change the AgentStatus to Retired and the policies under that agent to another agent. Is MySQL query correct or do I make two queries instead?
This is in my html for showing agent in agentavia
This is the agentavia table to change status from active to retired
This is policy1 table where policyAgent will change to another agent name as they click the retired button.
Code for changing data in mysql
router.get("/retire/:id", function (req, res, next) {
const AgentId = req.params.id;
const sql = `SELECT * FROM agentavia WHERE id= ${AgentId}`;
db.query(sql, function (err, data) {
if (err) throw err;
res.render("modifyagent", { title: "Agent List", editData: data[0] });
});
});
router.post("retire/:id", function (req, res, next) {
const sql = `UPDATE * from agentavia and policy1 WHERE id= ? and agentStatus = 'Retired' and
policyAgent = 'Vani'` ;
db.query(sql, function (err, data) {
if (err) throw err;})
alert("New agent shall take over your policies");
});
});

Related

Node.JS - SQL Injection in URL parameters?

I'm trying to learn Node.js and I'm currently making an Express app (using ejs) that will return values from a MySQL database, depending on the URL the user visits.
For example, visiting http://localhost:3000/test will list all users from the db table users. And the link http://localhost:3000/test/3 will return information about the user with the id number 3.
My code for: /test
app.get("/test", (req, res) => {
let sql = "SELECT * FROM users ORDER BY name";
db.query(sql, function (err, results, fields) {
if (err)
logmessage(err.message);
res.render("test", { data: results });
});
});
And here is the code for /test/:id
app.get("/test/:id", (req, res) => {
var userId = req.params.id;
let sql = "SELECT * FROM users WHERE id = " + userId;
db.query(sql, function (err, results, fields) {
if (err || !results.length) {
res.redirect("/");
} else {
res.render("test_user", { data: results });
}
});
});
My question is: is this safe? When I previously worked in PHP development, I used to prepare statements before making any queries.
What happens if a user changes the URL from: http://localhost:3000/test/3 and inserts some SQL injection code at the end of the url? Can the database be breached?
This will be for a live app on the web, so it's important no SQL injection can be made. I also want to add a form later on (req.body instead of req.params) that I also need to sanitize.
Or is there a built-in "prepared statement" already in Node?
SQL injection is prevented if you use placeholders:
let sql = "SELECT * FROM users WHERE id = ?";
db.query(sql, [userId], function (err, results, fields) {...});
Have you tried to implement Sequelize? From what I read ORMs prevent SQL injection. Also, it's pretty easy to use :)

How to make more than query in the same axios in Node js?

I want to add TeacherSSN & SectionNameID to the table (section), this is the database:
My question is what wrong in this code in the back end (Node js, MySQL, Express)?
app.post("/addSection", (req, res) => {
const TeacherName = req.body.TeacherName;
const SectionName = req.body.SectionName;
const SSN;
db.query(`SELECT SSN FROM user WHERE FullName = "${TeacherName}"`, (err, result) => {
if (err) {
console.log(err)
} else {
SSN = result;
console.log(result)
}})
const ID = db.query(`SELECT ID FROM sectionname WHERE SectionName = "${SectionName}"`);
console.log(SSN);
console.log(ID);
db.query(`INSERT INTO section(TeacherSSN, SectionNameID) VALUES (?,?)`,
[SSN, ID],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
)
})
How can i get the SSN and ID? To add them to the section table.
Several remarks about your code:
The assignment SSN = result happens asynchronously, after the first database query is completed, but you want to use the value of SSN in the INSERT statement, which is executed synchronously. In other words: The first query is sent, then the second query is sent, then the INSERT statement is sent, all synchronously. Only later do the responses for the two queries come in, asynchronously. That's when the (err, result) => ... functions are executed. So SSN receives its value after it has been used.
result does not contain the SSN value directly. According to the mysql documentation, you must write SSN = result[0].SSN;
Your second query const ID = db.query(...) uses a different form, without the (err, result) => ... callback function. In this form, it returns a promise, not the section ID that you expect.
You create the SQL queries through string operations, which exposes your database to the risk of SQL injection. Use placeholders (?) instead.
How is the database field sectionname.ID filled during the insert operation?
Can you be sure that the FullName and SectionName are unique in their database tables?
Assuming they are unique and the sectionname.ID is generated by the database automatically, you can perform the insertion with a single SQL statement:
db.query(`INSERT INTO section(TeacherSSN, SectionNameID)
SELECT user.SSN as TeacherSSN, sectionname.ID as SectionNameID
FROM user, sectionname
WHERE user.FullName = ?
AND section.SectionName = ?`,
[req.body.TeacherName, req.body.SectionName],
(err, result) => ...);
This obviates the need to wait for the result of a query before you make an insertion.

Node mysql in Discord.js returns empty result/array

I'm trying to make a command that get the selected queries from a table where the id is the one i use in the command, for example: !db 1 but I'm having a problem.
The problem is that the result is empty.
My code:
const Discord = require('discord.js');
const mysql = require('mysql');
module.exports.run = async (bot, message, args, connection) => {
const asd = args.slice(1,2).join(' ');
let querystring = `SELECT * FROM test WHERE id = '${asd}'`
connection.query(querystring, function (err, results, rows) {
if (err) throw err;
console.log(results);
});
}
module.exports.help = {
name: "db"
}
I appreciate any help! Thanks!
From the screenshot you posted earlier, your id column is a type INT. This code is searching as if the column is a VARCHAR.
Try this:
const id = args.slice(1, 2).join(' ');
if (isNaN(id)) { return; } // if the input isn't a number
connection.query(`SELECT * FROM test WHERE id = ${Number.parseInt(id)}`, (err, res, rows) => {
if (err) throw new Error(err);
console.log(res);
});
Important: This code allows SQL Injection. Template literals do not protect against this.

Node Express MySQL multiple routing

I want to make an route with multiple parameters using Node Express MySQL. Is it possible to do this with traditional url parameters like: page?id=2&user=10
Here is a simple query, but the only way of doing it so far is like this: page/2/10
app.get("/get-page/:id/:user", function (req, res) {
let sql = "SELECT * FROM table WHERE id= '${req.params.id}' AND userid= '${req.params.user}'`;";
let query = db.query(sql, (err, results) => {
if (err) throw err;
res.send(results);
});
});
This is just an example.
The reason I would like the traditional way is because, with the "slash" method the parameters always have to come in the correct order, or did I miss something?
Perhaps use the query property of the request to access the query string, as in req.query.id:
app.get("/get-page", function (req, res) {
console.log('ID: ' + req.query.id)
});

how do I access the result(object) of a get request using express?

Here is my get request made to a mysql table
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
console.log(results);
}
});
res.render('index');
});
As it stands, this function allows me to grab the information I want from the table and I can read the results via console.log. However, I'm unable to access results on my index.ejs page.
How do I access results(which is an object that contains the stuff I want) in my index.ejs file? Whenever I try to access results, it says that results in undefined. How do I make sure that the object that is created as a result of the call to the table is able to be used/accessed on a different page. For the time being, I would just like to create a simple table that has the keys in one column and the values in a second column.
You need to modify your code as below. The reason is db.query is an async operation and you are trying to render before the async request completed. Also, to be able to reach the result at your template engine, you need to pass the results to the render. (index.ejs)
app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
if(err){console.log(err);}
else{
res.render('index', results);
console.log(results);
}
});