Node.js doesn't execute code after MySQL Query - mysql

I have no idea what I did wrong, it's supposed to output onto console "Query Initiated" after it grabs the result but nothing is logged and I have no idea what I did wrong. Yes, I know the syntax is ugly, I ran a prettifier over it and now it is incredibly ugly and I am too lazy to manually go through 200+ lines of code to fix it.
connection.query(`SELECT * FROM pedodb WHERE ID='${msg.author.id}'`),
function (err, result) {
query.on('result', function (err2, result2) {
callback(null, rows, fields);
console.log("Query Initiated")

The callback should be associated with the query function.
And the practice of using parameters is that they should be in separate parameters otherwise there are chances that it can lead to SQL injection.
connection.query(`SELECT * FROM pedodb WHERE ID = ?`, [msg.author.id],
function (err, result, fields) {
callback(null, rows, fields);
console.log("Query Initiated")
})

Related

Why is my node.js POST command not executing mySQL command correctly?

I am trying to write a simple login page using node.js, HTML, and MySQL. A problem I ran into was adding entries to my sql db.
con.connect(function(err) {
if (err) throw err;
});
app.post('/create', function(req, res) {
var info ={
"usernamec":req.body.USERC,
"passwordc": req.body.PASSC
}
con.query('INSERT INTO users SET ?',info, function(err, result){
console.log(result);
});
});
Everything seems to be working except for the actual query, which returns undefined. What could I be doing wrong? The picture below is my database.
solution:
Change or Modify in Column name when you can assign the values (usernamec, passwordc) this one.
let info ={"username": req.body.USERC,"password": req.body.PASSC}
whenever you can insert the data Column name will be same as the Database table Col name.means Both are same not different
Firstly, please check your request params(USERC, PASSW)DataType and
Values.
then Second thing, console the error
con.query('INSERT INTO users SET ?',info, function(err, result){
if(err)
console.log(err);
console.log(result);
});
});
InCase Query Error you can get and resolved it.
Another Simple Way runs the Query in PHPMyadmin Manually.
Example:
INSERT INTO users SET `username`= 1 and `password` =`HELLO MYSQL`;

Query from MySQL's database returns [Object] [Object] in node.js and JSON.stringify() do not seem to work

I am using MySQL database and have created table that stores user's characters names from my Discord Bot.
I want my bot to display this list on Discord after using command, but it just returns [object Object].
I tried JSON.stringify() but it doesn't work. Is there something more to it I don't know about?
con.query (`SELECT Name FROM ${message.author.username}list`, (err, rows) => {
if(err) throw err;
JSON.stringify(rows);
message.reply(rows);
Both with and without stringify result are as in the picture]
you should save rows data in some variable. after update you code:
con.query (`SELECT Name FROM ${message.author.username}list`,
(err, rows, fields) => {
if(err) throw err;
rows = JSON.stringify(rows);
message.reply(rows);
}

SQL result lengths and showing nothing when searched

I want my Discord bot to check if a user that joined exists in a MySQL table. However, when it sends the query, it's basically telling me that it doesn't exist even though it should.
This is my current code:
bot.on('guildMemberAdd', async (member) => {
console.log(member.id)
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`
let result = connection.query(query)
if(result.length > 0){
console.log("It works!")
}
})
Node is asynchronous, so here you try to console.log result before it has been populated...
You'll find more info in this here :
Node JS MySQL query function not returning result
How do I return callback of MySQL query and push to an array in Node.js?
Here is the code with a callback function. Try it, it should work:
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`
connection.query(query, function (err, result) {
if (!err) {
if (result.length > 0) {
console.log("It works!")
}
}
});
Explanation:
As BadSpencer has stated, the mysql driver is asynchronous, and based around callbacks.
Say you're planning on picking your friend up to go to a sporting event. You're not sure when they want you to come, so you call them on the phone and ask them. They think about it for a while, and then tell you a time. You got the information you requested, so you hang up. In programming terms, this would be an example of synchronous code (sometimes thought of as "normal" code in Node.js).
Put yourself back in the same situation. However, when you call your friend this time, they're very busy. You don't want to bother them so you ask them to call you later. You hang up, but now you wait. An hour later, they call you back and tell you the time. This is the thought process of asynchronous code.
There's a lot more that goes on behind the screen, but for simplicity's sake, I'm not going to bombard you with all that information in this answer.
Solutions:
You should pass a function to act as a callback which will use the returned data. Consider this example:
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`;
// Passing the callback function as the second parameter.
connection.query(query, (err, result) => {
if (err) return console.error(err);
if (result.length > 0) console.log('It works (it actually does).');
});
However, this callback-based nature can become a nightmare due to the scope of the result and subsequent flow of the code. After a few queries, your code can become messy. To prevent this, you can wrap the query in your own Promise (or use a Promise-based version of the mysql package, like promise-mysql) and await the calls.
Here's an example setup:
// Defining 'connection' as a parameter so
// you can export this function and use it
// anywhere.
function query(connection, sql) {
return new Promise((resolve, reject) => {
connection.query(sql, (err, result) => {
if (err) reject(err);
else resolve(result);
});
});
}
// Asynchronous context needed for 'await' (this needs to be within an async function).
let query = `SELECT userId FROM QR5PVGPh1D.users WHERE userId = '${member.id}'`;
let result = await query(connection, query)
.catch(console.error);

Node.js, After inserting not shown in list query

After adding a product to the mysql database, I want to dump all the products with the latest product. This product is being added with an algorithm to the database and I want to list all the products immediately afterwards. Already tried "async", "promise" etc.
--When the table is empty--
connection.query("INSERT INTO `products` (id, name, price)", function (error, results, fields) {}); //inserted one row
connection.query("SELECT * FROM `products`", function (error, results, fields) {}); // show only []
after second insertion list query show only first row but not second. The main problem is this and table has two rows.
Thank you.
Query data when insert is done:
connection.query("INSERT INTO `products` (id, name, price)",
function (error, results, fields) {
connection.query("SELECT * FROM `products`", function (error2, results2, fields2){});
});
connection.query("INSERT INTO products(id, name, price)",
function (error, results, fields) {
if(error) return ....
else{
connection.query("SELECT * FROM products", function
(error,results,fields2){
var returned_data = results;
console.log(results);
//res.send(results);
})
}});
Would be the way to go, but check whether you're inserting the data the right way at all, since you haven't provided the way you do it, I doubt that any async method would fail you itself.
EDIT on request: You can pass the results to a variable, but you can only use it inside that function if you don't (because of its scope) , ie res.send or res.end it (if you're using this inside a request, which I'm guessing you are), or console.log it or just write it to a file.

Nodejs delete from table but select not working

user_id=3;
//Delete from table query working perfect
db.query("DELETE FROM table WHERE user_id=" + user_id, function(dberr,dbres){
addUserInventories(detail, req, function(err,invres){
getHomePageDataWithInvntory(req, function(request, response){
callback(null, response);
});
});
});
//Here add record in table
function addUserInventories(detail, req, callback){
//After insertion called following and working perfect
return callback(null, null);
});
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
db.query("SELECT * FROM table WHERE user_id=" + user_id, function(err, results){
callback(null, results); //Here result getting empty array
});
});
In above code Delete record and Insert record work perfect but Retrieving record is not working.
Note : There is no any syntax error in SQL Query and In log file it print SELECT * FROM table WHERE user_id=3
When I got this kind of error, I always save them with the same process :
console.log your query string before using it
Use a database client like Sequel Pro, MySQL Workbench for sql
Copy paste your query manually in the client and run it
Generally, you'll get a syntax error, just solve it in the database client and your solution should work
Database client is not mandatory as you can run the query with command line, but the client will be a simpler interface for you and is more likely to give you more details on your syntax error.
Can you try this process ? If you don't succeed in solving the syntax error in the database client, you can put the query here so we can help you
Just in case : with your example, I'll use this pattern to log the query if you have trouble to do it, this give you an idea of how to do it in your code
//Here retrieve record from table but not getting result after delete and insert operation
function getHomePageDataWithInvntory(req, callback){
user_id=3;
var queryString = "SELECT * FROM table WHERE user_id=" + user_id;
console.log(queryString);
db.query(queryString, function(err, results){
callback(null, results); //Here result getting empty array
});
});