Nodejs Update SQL DB based on parameter from URL - sql

Anyone able to help me out on this code .. What i expect to happen is when i hit thie URL I want it to update the DB Table with the user_name that is passed in the URL
Example: A user goes to /update/michael then I expect it to update the surname to Bloggs where the user_name is michael
app.get("/update/:user_name", function(req , res){
var user_name = req.params.name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= + 'req.params.name'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});

I updated the code please try this and let me know in comments if it's not work.
app.get("/update/:user_name", function(req , res){
var user_name = req.params.user_name;
sql.connect(config, function() {
const request = new sql.Request();
request.query("UPDATE table SET surname = 'Bloggs' WHERE user_name= '"+user_name+"'", (err, recordset) => {
res.end(JSON.stringify(recordset));
});
});
});

Related

Sequelize : How to query posts list from user id list?

To learn a little bit how a back end application works i'm currently creating a small instagram-like app using nodejs and sequelize (reactjs for the front).
I have 3 SQL tables :
Users
id (pk)
username
email
password
Posts
id (pk)
userId (fk)
message
mediaUrl
Following
id (pk)
userId (fk)
followingId (fk)
I would like to know what is the cleanest way to retrieve posts from an array of followingId corresponding to a userId ?
I just found a way to achieve what i wanted :
const db = require("../models");
const User = db.users;
const Post = db.posts;
const Following = db.followers;
const Op = db.Sequelize.Op;
exports.requestPost = async (req, res) => {
const followers = await Following.findAll({
where: {
userId: req.body.userId
},
attributes: [
['followingId', 'followingId']
]
});
const result = await followers.map(x => x.followingId);
const posts = await Post.findAll({
where: {
userId: result
}
});
return res.send(posts)
}

SQLite3 Database is not a constructor

So in my project I am trying to gather simple Discord username and unique identifier from discord and store it in SQLite database file. I get the error:
` let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
^
TypeError: sqlite.Database is not a constructor`
Here is my code in my index.js
// Requirements
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
const ServList = client.guilds.cache.size;
const sqlite = require('sqlite3').verbose();
require('dotenv').config()
//client login function
client.login(process.env.TOKEN);
// Start up Check list
client.once('ready', () => {
//Log and Set Status
console.log('Bot Online');
client.user.setActivity(`Proudly in ${client.guilds.cache.size} servers`, {
type: "WATCHING",
}, 60000);
//Database Initialization
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE | sqlite.OPEN_CREATE);
});
Here is my code for the command that is creating the error:
const Discord = require('discord.js');
const sqlite = require('sqlite3').verbose();
module.exports = {
name: 'create',
description: "Create your account!",
use(message, args, client, sqlite){
// Data to Add
let userDB = new sqlite.Database('./disco.db', sqlite.OPEN_READWRITE);
userDB.run(`CREATE TABLE IF NOT EXIST usersInfo(userID INTEGER NOT NULL, uNameR TEXT NOT NULL)`);
let userID = message.author.id;
let uName = message.author.tag;
let uQuery = `SELECT * FROM usersInfo WHERE userID = ?`;
userDB.get(uQuery, [userID], (err, row) => {
if (err) {
console.log(err);
return;
}
if (row === undefined){
userDB.prepare(`INSERT INTO usersInfo VALUES(?,?)`);
insertdata.run('userID, uName');
insertdata.finalize();
userDB.close();
} else {
let userID2 = row.userID;
let yName = row.uNameR;
console.log(yName, userID);
}
});
message.channel.send('success');
}
}
Edit: Your question has been identified as a possible duplicate of another question. If the answers there do not address your problem, please edit to explain in detail the parts of your question that are unique.
The suggestion solution does not work for me as the suggested answer utilizes mySQL while I use SQLite3, Not only that but the suggested answer attempts to connect to a hosted database while mine is local.

Node js TypeError: Cannot read property 'nick' of undefined

The Issiue
Issue is basically if i try to combine query+variable or put it in "fake pdo" style, it does not work.
Code
if(page == "profile"){
var user = "Failed to load.";
con.query('SELECT * FROM users WHERE id = '+con.escape(parseInt(userIDRequested)), function (err, result, fields) {
//console.log(result);
user= result[0].nick;
io.emit('userinfo', { nick: user});
});
}
app.get("/user/:start", function(req, res){
page = "profile";
var user_id = req.params['start'];
pageid = user_id;
if(didshitgetupdated == false){
useridRequested = pageid;
didshitgetupdated = true;
}
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
finishConnection(res);
})
but for some reason i get this:
TypeError: Cannot read property 'nick' of undefined
at Query.<anonymous> (D:\bricktalenode\bricktale.js:36:29)
at Query.<anonymous> (D:\bricktalenode\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (D:\bricktalenode\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (D:\bricktalenode\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (D:\bricktalenode\node_modules\mysql\lib\protocol\Protocol.js:38:16)
Things i tried
making a if condition to check it
(did not helped)
connecting database using another thing
i used same query(changed variable for php though) in php to access, query is ok, so issue on my node.js code then.
waiting for some time ( did not helped)
parse int
nothing really helped that i done
but for some reason i get stuff correctly using console.log(result);
but i cant fetch them using the code.
The results
[ RowDataPacket {
nick: '[MODERATED 5]',
id: 5,
password: 'fdaf40dc5531c0acf82911892f552f0a',
banned: 0,
coins: 0,
registerdate: 2021-05-10T02:55:45.000Z,
status: 'BETA STATUS',
rank: 'Player',
rep: 1,
token: 'token',
lastonline: '2021-05-10 03:05:08',
lastdaily: 2021-05-19T07:04:34.000Z } ]
but i cannot access it
app.get("/user", function(req, res){
page = "profile";
res.writeHeader(200, {"Content-Type": "text/html"});
let btlib = btNetLib(res);
btlib.btSend(navbar);
btlib.btSendFile("profile/index.html");
var sql = 'SELECT * FROM users WHERE id = ?';
con.query(sql, req.query.id, function (err, result) {
if (err) throw err;
setInterval(() => {
var bricklet;
bricklet = result[0].nick;
console.log(bricklet);
io.emit('userinfo', { nick: bricklet});
},150);
});
finishConnection(res);
})
moving stuff inside of my app.get solved it.

Insert session data into postgres database in Nodejs Expess app

I have an Nodejs express function where I am trying to insert data that is stored in the browser session into my postgres database. When I have the insert statement like this, the insert works but the session-stored customer_id isn't inserted and is just left null.
On the line with "var sql = INSERT INTO journal....", the values $1 and $2 are from user input and work correctly.
How can I get value 3 of the customer_id stored in the session to insert correctly? I would appreciate any advice or greater understanding.
app.post("/addJournalEntry", addJournalEntry);
function addJournalEntry(req, res) {
console.log("Posting data");
// var id = req.query.id;
//body is for post, query is for get
const customer_id = req.session.customer_id;
const journal_entry_date = req.body.journal_entry_date;
const journal_entry = req.body.journal_entry;
const params = [journal_entry, journal_entry_date, customer_id];
addEntryFromDataLayer(params, function (error, addEntry) {
console.log("Back From the addEntryFromDataLayer:", addEntry);
if (error || addEntry == null) {
res.status(500).json({
success: false,
data: error
});
}
else {
// res.json(result);
res.status(200).json(addEntry);
}
});
}
function addEntryFromDataLayer(params, callback) {
console.log("addEntryFromDataLayer called with id");
var sql = "INSERT INTO journal (journal_entry, journal_entry_date, customer_id) VALUES($1::text, $2::text, $3)";
// var params = [id];
pool.query(sql, params, function (err, addEntry) {
if (err) {
console.log("error in database connection");
console.log(err);
callback(err, null);
}
console.log("Found DB result:" + JSON.stringify(addEntry));
callback(null, addEntry);
});
}

Difference between where and like in CLEARDB

I'm trying a simple nodejs login system and want to use the following query:
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
But it simply doesn't return anything so I had to do it like this:
'SELECT * from admin_cred where username like "%'+username+'%" AND password like "%'+password+'%"'
This is the code segment:
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?' AND password = '?'", [username], [password]
// 'SELECT * from admin_cred where username like "%'+username+'%" AND password like
"%'+password+'%"'
);
Can anyone point out why the first query is not working?
And the difference bertween the two statements?
N.B: This is the first time i'm using cleardb on heroku and a few things seems different from MySql. Everything else in the code works so I've narrowed the problem down
EDIT 1
I just noticed that the second query is running even though the password was wrong
UPDATE 1
Here is the node js code as requested:
class auth {
constructor(app, database) {
this.login(app, database);
}
//http://localhost:8000/api/auth/v1/login
login(app, database) {
app.post("/api/auth/v1/login", async (request, response) => {
const username = request.body.username;
const password = request.body.password;
try {
const result = await database.query(
"SELECT * FROM admin_cred WHERE username = '?'", [username]
);
console.log(result);
if(result.length > 0){
if(password === result[0].password){
response.json({
loggedIn:"true",
data: username
})
}else{
response.json({
loggedIn:"false",
data: "wrong username or pass"
})
}
}else{
response.json({
loggedIn:"false",
data:"username doesnt exist"
})
}
} catch (error) {
console.log(error);
}
});
}
}
And here is the post request from ReactJs:
const handleLogin = async (e) =>{
e.preventDefault();
const admin = {username, password};
const response = await axios.post(
"http://localhost:8000/api/auth/v1/login",
admin
);
if(response.length > 0){
console.log("response: " + response);
}else{
console.log("no response")
}
};
Use:
const result = await database.query(
'SELECT * FROM admin_cred WHERE username = "?" AND password = "?"', [username, password]
);
Tip: never use LIKE for authentication queries and try to encrypt passwords.