I've been working with mysql in nodejs for a bit and I can't seem to figure out how to use the query with multiple where statements.
Like:
SELECT * FROM user_information WHERE a=a or b=b
Right now i have this as my code:
connection.query("SELECT * FROM user_information WHERE username=" + registerarray[1] + " OR email=" + registerarray[3],function(err, results){
if (err){console.error(err);}
});
Thank you and best regards
Me
results is rows of response from mysql.
Let's simplify parts:
const
q = "SELECT * FROM user_information WHERE username=? OR email=?", // You can use placeholders like ? marks
args = [registerarray[1], registerarray[3]]; // array of values that will be set to placeholders (will be escaped for security)
connection
.query(
q, // our query
args, // placeholder values
(err, records) => { // query response scope begins here
if (err) {
console.error(err);
}
console.log('THIS IS RESULT OF QUERY EXECUTION:');
console.log(records); // this is result, already fetched array
});
Related
I have a segment like the following:
sql.query("SELECT * FROM tasks WHERE groupId = ? AND completed = 0", res[0].groupId, (err, res) => {
if (err) {
console.log("Error selecting from TASKS: ", err);
return result(null, res);
}
console.log("tasks: ", res);
return result(null, res);
})
In this case, you can see how the results of a previous query ( res[0].groupId ) are being plugged into the statement shown here, and it works.
I want to add another query after this one which will use a similar structure, statement something like: "SELECT * FROM updates WHERE taskId = ?". In this case, I want to use ALL of the task IDs resulting from the previous statement to plug into this query. How do I do that? I envision something like res[*].taskId in my head - no idea if that works, but that should give you the idea.
I have a json request in this form:
{
"claimNo":["5454545","4554454","45884"]
}
the claimNo could hold any number of items(not restricted). I want to get the values and write a query to fetch data from a mysql db where claimNo = the values in the request.
sample response:
"claims": [
{
"claimNo": "4554454",
"ClaimCause": "gjgiukhknl",
"ClaimAmount": 45550,
},
{
"claimNo": "5454545",
"ClaimCause": "fdfdfdfdf",
"ClaimAmount": 0,
}
]
I can successfully loop through the request and display on terminal or even insert into the db with multiple ORs but that only works for a restricted array length.
req.body.claimNo.forEach(element => {
// console.log(element)
let sql = 'SELECT * FROM claims WHERE claimNo = ?'
connection.query(sql,element,(err, rows, fields) => {
if(!err){
// return res.json({
// success:true,
// errorCode:"",
// errorDescription:"",
// claims:rows
// })
console.log(rows)
}else
console.log(err)
} )
})
If I understand your question correctly, you're looking for a way to query MySQL database for multiple number of claimNo entries, and return the result as a single result.
Using MySQL IN() operator, you can write your query as select * from claims where claimNo in(?)
let sql = 'select * from claims where claimNo in(?)';
let claimNos = req.body.claimNo;
connection.query(sql, claimNos, (err, rows, fields) => {
if(!err){
// return res.json({
// success:true,
// errorCode:"",
// errorDescription:"",
// claims:rows
// })
console.log(rows)
}else
console.log(err)
})
You don't need to send a separate request for each claimNo. You can you the IN operator instead. The following should work:
const claimsNo = claims.map(claim => claim.claimNo);
const sql = 'SELECT & FROM claims where claimNo IN (?)';
connection.query(sql, [ tableName, claimsNo ], (err, rows, fields) =>{
...
});
Am retrieving values from database using nodejs.
I implemented mysql like query via prepared statement to ensure that sql injection attack is eliminated. my problem is that it does not retrieve any result. it just show empty results in the console please can someone point to me what is wrong with the query
exports.autosearch = function (req, res) {
//var search = req.body.searchText;
var search = 'bukatti';
//db.query('SELECT * FROM users WHERE name like ?', ['%' + search + '%'], function (error, results, fields) {
db.query('SELECT * FROM users WHERE name like ?', ['%search%'], function (error, results, fields) {
console.log(results);
});
}
Thanks
I have found out my problem. i added the error log and discover that the was type error somewhere. This fix it anyway
db.query("SELECT * FROM users WHERE name like ?", ['%' + search + '%'], function (error, results, fields) {
Thanks
I am using nodejs and the mysql npm package and I'm trying to select from a table where other_text =
Here is what it looks like:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
attributeName.other_text, function (err, rows) {
...
I have read that using ? will automatically escape the user entered string. In most of the examples that I see that do this, they have brackets around the 2nd parameter in the query function, like below:
var query = connection.query(`SELECT id FROM ${tableName} WHERE other_text = ?`,
[attributeName.other_text], function (err, rows) {
...
Are the brackets necessary in order to escape the string that's passed in? It works when I try it, but I don't even know how to test a SQL injection so I don't really know if the brackets are necessary or even correct.
Thank you.
The brackets represent an array. You can use an array in case you have more values you want to use with your query.
For example, let's say that you want to select multiple columns from the table, and you want to pass them to the statement, you would use something like this:
connection.query(`SELECT ?? FROM ${tableName}`,
[col1, col2, col3], function (err, rows) {
It also does work in combination with strings, numbers or even objects. Let's say that you want to update the user with id 1 from Users table table. You would do something like this:
const tableName = 'users';
const whereCondition = {id: 1};
const whaToUpdate = {name: 'newName'}
const mysql = require('mysql');
const statement = mysql.format('update ?? set ? where ?', [tableName, whaToUpdate , whereCondition]);
I also recommend using .format for better code reading.
Finally you would have something like this:
connection.query(statement, (error, result, fields) => { });
The bracket uses for passing multiple values. You can use escape function or question mark (?) placeholder to prevent SQL injections. Lets have a look in details:
We are using mysql node module to provide all example below (Example 1 to Example 5). The below code is necessary to follow those example.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
MySQL con.query has overloaded function.
Example 1: it takes sql string and callback function
var sql = 'SELECT * FROM customers;
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
Example 2: it takes sql string, parameter and callback function
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);
});
In Example 2, the second parameter uses [ ] so that you can pass
array to provide multiple values as parameter. Example 3 shows how to pass multiple values in second parameter.
Example 3: Here two values are passed name and address into [ ]
var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
if (err) throw err;
console.log(result);
});
Preventing SQL injections
To prevent SQL injections, you should use escape function the values when query values are variables provided by the user.
Example 4: 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);
});
Example 5: 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);
});
More details
if I have a query like the following:
var queryString = "INSERT INTO pid SET title = '" + randomTitle + "', poc = '" + random + "';"
connection.query(queryString, function(err, rows, fields) {
...(do something here)
});
, is there a way I can retrieve information for the just-inserted row without performing a new query (in my particular case, I want the auto-generated primary key value).
For instance, can I use the construct with the "query" object (below) and then perhaps use one of the query.on callback to retrieve the information about the just-inserted row?:
var query = connection.query(queryString, function(err, rows, fields) {
query.on('fields', function(fields) {
... get the field information?
});
query.on('result', function(row) {
.. get the field information?
});
});
If not via the query callbacks, is there another way? Thanks for any response!
According to docs it is possilbe. Notice that callback function of insert query does not have rows and fields but only result parameter:
connection.query(queryString, function(err, result) {
if (err) {
// handle error
}
console.log(result.insertId); // prints inserted id
}
Your query is also vulnerable to sql injection. It should look like this:
var queryString = "INSERT INTO pid SET title = ?, poc = ?";
connection.query(queryString, [randomTitle, random], function(err, result) {
// ...
}