I'm trying to get results from multiple tables with one request from client. I first tried JOIN, but that would mean I'd have to have multiple rows that contain duplicate information. Then I decided to do a different query for each table separately, although I'm not sure know how cost efficient this is.
How should I construct the query so that it is accepted by Node.js? The one I'm trying to use now doesn't work if I don't use quotation marks to wrap the whole query, but if I do use them it complains there is an error with my query.
Here is the code for the query.
sql = "'SELECT * from `Ilmoittautuminen` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus); 'SELECT * from `Jasenmaksu` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus); 'SELECT * from `OppOikeus` WHERE `optunnus` LIKE ' + mysql.escape(reg.body.optunnus);"
console.log(sql);
connection.query(sql, function(err, rows){
console.log(rows)
if(err){
console.log(err)
res.json({
success: false,
message: err,
});
}else{
queryResponse(res, rows);
}
});
taking reference of https://github.com/mysqljs/mysql
passs multipleStatements:true in your connection param
and try with an exmaple
conn.query(`
SELECT * FROM posts limit 1;
SELECT * FROM Users limit 1;
`, (err, results)=>{
console.log(err, results)
});
Related
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")
})
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.
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
});
});
I have the following query that I'm using in the query function (https://github.com/mysqljs/mysql#escaping-query-values) :
database.query("UPDATE Project SET Content = 'Hello ?' WHERE Id = ?", [id], function(err, rows, fields) {
if (err) {
console.log(err);
res.json({ status: 'FAIL QUERY' });
} else {
res.json({ status: 'SUCCESS' });
}
});
I have an error because it is replacing the question mark on "'Hello ?'" and "WHERE Id = ?" and he only have one attribute : [id].
How to avoid this ?
You have various options:
database.query("UPDATE Project SET Content = ? WHERE Id = ?", [ 'Hello ?', id], function(err, rows, fields) { ... })
Or:
database.query("UPDATE Project SET Content = 'Hello ?' WHERE Id =" + mysql.escape(id), function(err, rows, fields) { ... });
I would report this as a bug to that project. They should not replace the ? characters when those character appear:
Inside string literals, as in your example.
Inside delimited identifiers. It's uncommon, but legal SQL, to use punctuation symbols as part of a table name or column name.
Inside comments.
If that Node.js project is replacing the ? regardless of context, then this is an unacceptable bug.
I would stop using that package until they fix the bug.
Thanks for all your answer ! I learned a lot.
The robertklep answer using (mysql.escape(id)) worked for me.
However I found another way that I'm sharing with you for adding multiple parameters to the query :
You can create a JSON called queryJSON and adding to it key - value. Ex : queryJSON = {Content: 'Hello ?', Address: '742 Evergreen Terrace'}. And then :
database.query("UPDATE Offer SET ? WHERE Id = ?", [queryJSON, id], function(err, rows, fields) {
This is usefull for my put request for adding one or more paramters to the request.
Prepared statements will replace each instance of ?, in order, with the elements in the passed array, also in order. You will need to use a different placeholder character if you want to keep it as a placeholder, or have 2 elements in the array, the first being what the ? after Hello will be replaced with (bear in mind that it will also put single quotes around that element) and the second one for Id = ?
Preventing SQL injections
Escape question mark characters as placeholders for MySQL query in NodeJS is used to prevent SQL injections (Example 1). You can use escape function to do the same (Example 2).
To prevent SQL injections, you should use escape function the values when query values are variables provided by the user.
Example 1: Escape query values by using the placeholder ? method
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
Example 2: Here we used escape function to avoid SQL injections
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' + mysql.escape(adr);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
More details
Good day,
I am willing to retrieve the id value of a freshly inserted row in Mysql.
I know there is mysqli_insert_id function, but:
I can't specify the table
Maybe there would be a risk of retrieving the wrong id, if a query is made in the meanwhile.
I am using node.js MySQL
I don't want to take the risk to query the highest id since there are a lot of queries, it could give me the wrong one...
(My id column is on auto-increment)
https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
describes the solution perfectly well:
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result, fields) {
if (err) throw err;
console.log(result.insertId);
});
var table_data = {title: 'test'};
connection_db.query('INSERT INTO tablename SET ?', table_data , function(err, result, fields) {
if (err) {
// handle error
}else{
// Your row is inserted you can view
console.log(result.insertId);
}
});
You can also view by visiting this link https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
I think you misunderstood the use of mysqli_insert_id() method. This method must be executed immediately after the insert statement to obtain the last inserted id. if you do it my MySQL directly
INSERT INTO(a,b)values(1,'test');
SELECT LAST_INSERT_ID(); -- this will display the last inserted id