Hi friends I have to ask the mysql query repeatedly in my application with Node js. I will shape the second interrogation according to the result of the first interrogation. The following code example does not work. Can you help me? You can support the functioning of the queries do not hang.
let sql = "SELECT COUNT(*) AS miktar FROM orders";
connection.query(sql, function(err, result) {
if (err) throw err;
let sqlAnother =
"SELECT COUNT(*) AS miktar FROM orders WHERE result=" +
result[0].miktar +
"";
connection.query(sqlAnother, function(err, result) {
if (err) throw err;
callback(result);
});
});
connection.end();
You can do this in one call with a subquery:
SELECT COUNT(*) AS miktar FROM orders WHERE result = (SELECT COUNT(*) FROM orders)
If this returns a result in the MySQL CLI, then your code must provide this result to callback. Otherwise it's just that no row in orders happens to have a field result that contains the exact amount of rows in the table.
Related
Socket.io, Node.js: How can a javascript variable be passed to mysql query from in a javascript.js?
There is an error when a variable of value '222.222.222.222', is attempted to be passed into the mysql query, but not when a variable having a value of '2' is passed into the same mysql query.
Any help would be greatly appreciated.
This gives error:
var javascriptVariable = '222.222.222.222';
$query = 'INSERT INTO misc_table (misc_field) VALUES ('+javascriptVariable+')';
connection.query($query, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
console.log("Query succesfully executed: ", rows);
});
This does not give error:
var javascriptVariable = '2';
$query = 'INSERT INTO misc_table (misc_field) VALUES ('+javascriptVariable+')';
connection.query($query, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query.");
return;
}
console.log("Query succesfully executed: ", rows);
});
Never ever thought to update databases in this manner.
First. In fact, you try to execute next code
INSERT INTO misc_table (misc_field) VALUES (222.222.222.222)
Second. This is the straight way to sql injection
Thrid. Try something like this
var javascriptVariable = '222.222.222.222';
let $query = 'INSERT INTO misc_table (misc_field) VALUES (?)';
connection.query(
$query,[ javascriptVariable ],
function (...args) {
....
}
);
SECOND EDIT
The issue was caused by the MAX_INTEGER_VALUE which is lower then the integer value I was passing. I changed the MySQL table column to TEXT instead of BIGINT and everything is being returned correctly.
Thanks for all the help!
EDIT
So I just realized that the userID variable and the guildID variables are being passed using this line of code.
mysqlModule.userCrewSearch(575783451018526744, 282997056438665217);
However the values that are being supplied to the SQL statement turn the last two digits of the number into '00'. So instead of 575783451018526744 the value being passed into the SQL statement is 575783451018526700.
So why is this value being changed when nothing I am doing in my code is changing these values?
Original Post
I'll keep this short and sweet. I'm trying to run a query using the nodejs MySQL package. I'm not sure where I'm going wrong but whenever I call my function that executes my query, I'm always returned an empty array, unless I hardcode the values into the SQL query.
Heres the code:
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=? AND `guildID`=?;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
I'm calling this function like so: userCrewSearch(575783451018526744, 282997056438665217);
Both of the values I'm passing are integers. However this is what I get in my console.
However, here is my code with the values hardcoded into the SQL... to which the code then returns the result in the form of a RowDataPacket.
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=282997056438665217 AND `guildID`=575783451018526744;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
Heres the result.
Bonus Question: How do I handle the RowDataPacket? Can I convert this directly into an object so I can call results.crewID and return just that value?
Same problem i was facing few days ago. I have solved this by converting the parameters into string.
function userCrewSearch(String(guildID), String(userID)) {
// your code here
}
Try adding + before your numeric parameter, it converts into number, it worked for me-
connection.query(sql, [+guildID, +userID], function(err, results) {
for your bonus questions answer, you can directly access the crewID or some other key using,
results[0].crewID
or do something like -
const [ result ] = results;
console.log(result.crewID)
I am running the below query in mysql db and i want to store the results in an array ? How can I do that in node.js ?
SELECT ProductName FROM products;
The last SELECT statement you have described is almost correct except that it uses structure for the INSERT statement.
Here is 2 correct ways to create and execute SELECT statements, the safe way, to avoid MySQL injections and to secure your database from possible attacks.
1. Multiple Records
/**
* Example of Selecting multiple rows form one MySQL table
*/
var query = connection.query('SELECT ProductName FROM products',
[product_id], function(err, results) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});
Using a prepared Statement targeting for specific rows:
/**
* Example of Selecting one record using MySQL Table ID
*/
var category_id = 5;
var query = connection.query('SELECT ProductName FROM products WHERE CategoryId=?',
[category_id], function(err, results) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});
Using mysql.escapeId() method
var category_id = x;
var sql = 'SELECT productName FROM products WHERE category_id = ' + connection.escape(category_id);
connection.query(sql, function (error, results, fields) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});
I'm having trouble executing my update query. Right now it's inside the select query witch works fine, the update queries are well formed, since I can copy paste a single update query from the output and it will update accordingly. no errors thrown, stream with update string appear but none are executed.
connection.connect();
connection.query('SELECT text, id from twits2 order by id ASC', function(err, rows) {
rows.forEach(function(row){
var id = row.id;
var r1 = sentiment(row.text);
var score = r1.score;
var comparative = r1.comparative;
var q = 'UPDATE twits2 SET score ="'+score+'", comparative ="'+comparative+'" WHERE id="'+id+'"';
console.log(q);
connection.query(q, function (error, results, fields) {
if (error) throw error;
});
});
All I want to do is insert some data if my database doesn't have that, so I put Insert SQL into my callback function of my Select SQL, but I got error like this:
{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
my code snippet is here:
db.query('SELECT count(*) as Resultcount FROM tablename WHERE email = ? and password = ?', [post.email, post.password], function(error, result){
if (result[0].Resultcount == 0){
var query2 = db.query('INSERT INTO tablename SET ?', [post], function(err, result) {
if(err){
console.log(err);
}
console.log(result);
});
}
else{
console.log('have data already');
}
});
Could someone give me some advice?
Thanks
----update----
actually, the callback function of select SQL is not an anonymous function, my code snippet about db.end() is like this:
var QueryResults = new queryResultFuntion(Back_results);
db.query('SELECT count(*) as Resultcount FROM tablename WHERE email = ? and password = ?', [post.email, post.password], QueryResults.queryResult );
db.end();
You db.end() call will queue the connection to close once the SELECT has completed, so when you attempt to do the inner INSERT query, the database connection will have been closed, hence the error PROTOCOL_ENQUEUE_AFTER_QUIT, as you are attempting to queue a new command after the connection is closed.
Depending on how you are creating the connection, you should either move your db.end() call inside the callbacks, or not have a db.end() call at all if the connection is opened on program start.