Problem with SELECT query (NodeJs and mySQL) - mysql

got a problem with simple user Login application. There goes the code.
exports.postLogIn = (req,res,next) =>{
const reqName = req.body.name;
const reqPassword = req.body.password;
console.log(reqName,reqPassword);
db.query('SELECT * FROM userinfo WHERE name = ? AND password = ?', [reqName, reqPassword], function(error, results, fields) {
console.log(results.toString());
console.log(error);
console.log('qirwoe');
res.end();
});
// User.userRequest(reqName,reqPassword, userInfo =>{
// console.log();
// if(userInfo.length>0){
// console.log('fail');
// // return res.render('user/fail')
// }
// console.log('aproved!');
// // return res.render('user/index',{user:userInfo,pageTitle:'Social Reporter',path:'/'})
// res.redirect('/');
// });
}
So, its not working at all, I dont get any response from console.logs or anything.
Here's what I observed,
SELECT *
FROM userinfo
WHERE name = 'Gui' AND password = '123465'
running this code on mySQL does work. I get a response back on mySQL workbench.
I can INSERT things normally on my DB. So the connection is working.
I did get the right req.body, so the input on '?' mysql command is right
I did the following command to import mysql 'npm install --save mysql2'
Anyway, dont know what else to do, let me know if I need to provide more info. Thanks for your all attention!

Problem solved!
By those who's having the same problem I will post my answer here.
So, by some researches I saw that it may be an async problem, and by #esqew comment as well.
Then I tried to remove those lines,
db.query('SELECT * FROM userinfo WHERE name = ? AND password = ?', [reqName, reqPassword], function(error, results, fields) {
console.log(results.toString());
console.log(error);
console.log('qirwoe');
res.end();
});
Which is the problem, and repleace to an async function:
async function loginAttempt () {
let [rows, fields] = await db.execute('SELECT * FROM userinfo WHERE name = ? AND password = ?', [reqName, reqPassword]);
console.log(rows);
}
loginAttempt();
Problem solved, be aware to sync/async funcions in mySQL querys. Again, correct me if I'm wrong with any information.
Hope I could help anyone.

Related

dynamic link not working when pulling info from mysql database

So my goal is to pull info from the database when a user logs in to have it in the URL for when they are logged into their account, I can get the information I am looking for but when I go to log in to the account I am getting this error
Cannot GET /main-component[object%20Object]
and this in the URL
http://localhost:3000/main-component[object%20Object]
I have tried different variations of writing my code and no matter what whenever I go to put the info into the redirect link I just get an error. I am connected to the database and getting data just not able to redirect to the next place on the website.I am new to nodejs so I'm not exactly sure what to do from this point. Thanks for the help and heres my code
let str
let testi
function output(rows){
str = rows
console.log(str)
return str
}
app.post('/login-validate', (req, res) =>{
// let user = userInfo(req.body.email, req.body.password)
// console.log(user)
testi = pool.query('SELECT * FROM users WHERE email=? AND password=?',[req.body.email, req.body.password], (err, res) =>{
if(err){
console.log(err)
}
output(res[0].first_name)
})
res.redirect('/main-component' + testi)
})
app.get('/main-component/:id', (req,res) =>{
res.render('calanderView')
})

API delete call for row from MySQL DB not work

I'd like to create api call from back-end for DELETE query from mysql DB but when execute it in browser get error
'Cannot GET ...'
I pass into the route id of row which had got from DB
At back-end the code is:
app.delete('/products/delete/:id*?', function(req, res) =>{
let { id } = req.query;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query}'`;
console.log("id: ", req.query);
// delete a row with id = req.query
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log("Deleted Row(s):", results.affectedRows);
});
});
But finally this call not works and row not deleted
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_db.products WHERE my_db.id= '${req.query.id}'`;
console.log("id: ", req.query.id);
Try using this.
fetch(url, {
method: 'delete'
}).then(response => response.json());
Try running this in your browser console. It should work.
Most likely you're making a GET call to a DELETE resource.
Please read Express 4.x. Can you share the code you're using to make DELETE request from browser?
I did some changes and now running version of the code looks like
app.delete('/products/delete/:id', (req, res) => {
let { id } = req.params ;
let DELETE_PRODUCT_FROM_DB = `DELETE FROM my_DB.products WHERE id= '${id}'`;
console.log('id: ', req.params);
// delete a row with id = req.params
connection.query(DELETE_PRODUCT_FROM_DB, (error, results, fields) => {
if (error) return console.error(error.message);
res.status(200).send(results);
console.log('Deleted Row(s):', results.affectedRows);
});
});
Also, I figured out that changes from req.query on req.params helped to get id from the link as a parameter

discord.js/node.js make code wait until sql query returns result

I am working on a discord.js bot, and I'm storing a bunch of information on various servers in a database. The problem is, that the code doesn't wait for the database to return the results. In the current situation, I'm trying to check if the server specific prefix checks out.
I tried using async and await at various places, but those didn't work. If I could, I'd rather not use .then(), because I don't really want to put all the commands inside a .then().
const { Client, Attachment, RichEmbed } = require('discord.js');
const client = new Client();
const mysql = require("mysql");
const config = require("./config.json")
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'botdb'
})
client.on("ready", () => {
console.log("I'm ready")
})
client.on("message", message => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let msg = message.content.split(" ");
let command = msg[0];
let prefix;
con.query(`SELECT * FROM serversettings WHERE ServerID = ${message.guild.id}`, (err, rows) => {
if (err) throw err;
prefix = rows[0].Prefix;
console.log(prefix)
})
console.log(`Prefix: ${prefix}, Command: ${command}`)
if (command === `${prefix}examplecommand`) {
//Do something
}
//Other code that uses prefix and command
}
It should log the prefix first, and then the Prefix: ${prefix}, Command: ${command} part, but it does it the other way around, so the examplecommand doesn't work.
Your result is caused by the fact that what's outside your query callback is executed immediately after the call. Keep in mind the mysql module is callback-based.
Possible Solutions
Place the code inside the callback so it's executed when the query is completed.
Wrap the query in a promise and await it.
function getGuild(guildID) {
return new Promise((resolve, reject) => {
con.query(`SELECT * FROM serversettings WHERE ServerID = '${guildID}', (err, rows) => {
if (err) return reject(err);
resolve(rows);
});
});
}
const [guild] = await getGuild(message.guild.id) // destructuring 'rows' array
.catch(console.error);
console.log(guild.prefix);
Use a Promise-based version of a MySQL wrapper, like promise-mysql. You could use it the same way as the code above, without worrying about coding your own Promises.
const [guild] = await con.query(`SELECT * FROM serversettings WHERE serverID = '${message.guild.id}'`)
.catch(console.error);
console.log(guild.prefix);

rely on the result of a query to run another nodejs mysql

Hey guys I have the following node code and it works fine
import express from 'express';
import connection from '../index.js'
const router = express.Router();
router.get('/allTemplates', function (req, res) {
let queryString="select count(*) as exist from users where userName='bob'";
let query = connection.query(queryString, (error, result) => {
if(error) {throw error;}
res.json(result);
})
});
module.exports = router;
what I want to do is react to this with something like
if(exists==1){error='sorry but that user already exists';} else {
queryString="insert into users (userName, email, address) values('bob', 'emailAddress#email.com', 'address')";
let query = connection.query(queryString, (error, result) => {
if(error) {throw error;}
res.json(result);
})
}
I come from a php background so this is all very new and the async of node freaks me out but I have to use it for my new job. How would I react to a result of one query and run another one based on the outcome.
I put the mysql library in a variable called database and I am using async await to run queries. In the database file I connect to the database and set up my variables like so:
const mysql = require("mysql");
const util = require("util");
const awsConfig = {
host: process.env.RDS_HOST,
user: process.env.RDS_USER,
password: process.env.RDS_PASSWORD,
database: process.env.RDS_DATABASE
};
const connection = mysql.createConnection(awsConfig);
connection.query = util.promisify(connection.query.bind(connection));
connection.end = util.promisify(connection.end.bind(connection));
module.exports = connection;
Than i use async await to run queries and use the results to run or not run others. like so:
let result;
let sqlStatement ="";
result = await database.query(sqlStatement);
let userExists = result[0].exist;
sqlStatement =
"SELECT COUNT(*) AS exist FROM user where userName=" +
database.escape(req.body.userName);
if(userExists==0){
result = await database.query("INSERT INTO user SET ?", [req.body]);
}
hope this helps someone else

Mysql search , express response issue

How write a code which will bring me items from MYSQL-DB which will match some of the letters with request? For example I write to the end of link "samsung" but the name of item is "samsung s9, s8 etc...". How to get all of items? This is my code which is note work.
app.get('/models/:name', (req, res, next)=>{
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE name=?'
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
You have to use wildcard character % like 'SELECT * FROM products WHERE name=%anyMobileName%'
IMO Instead of creating MYSQL query from your own and executing these use Sequelize ORM