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) {
// ...
}
Related
Im using Node JS to create random ethereum accounts and I would like to store them in the mysql database (yeah I know it's bad but that's not the point).
Insertion goes without errors, but when I look at the inserted data it looks unrecognizeable.
I've tried changing collation into various encodings but nothing helped. Also, this: res.setHeader('Content-Type', 'application/json; charset=utf-8');
CODE:
const newAcc = web3.eth.accounts.create();
con.connect(function(err) {
if (err || !newAcc) throw err;
console.log("Connected!");
var sql = 'INSERT INTO eth_accounts (addressEth, privateKeyEth) VALUES
('+newAcc.address+', '+newAcc.privateKey+')';
con.query(sql, function (err, result, fields) {
if (err) throw err;
console.log(result);
});
var sql = 'SELECT * FROM eth_accounts';
con.query(sql, function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
I've been using PHP so far and every time a string would look strange I would just slap use utf 8 command on top and it would work.
This is the error message that I'm getting:
????J????m~?G?ȓ?L^ as address, ?]??n?A*j?[|??-hޏ?gx?_>?{?-?| as
key...
Per comment discussion above, the solution was to use quotes around the strings:
var sql = "INSERT INTO eth_accounts (addressEth, privateKeyEth) VALUES ('"
+ newAcc.address + "', '" + newAcc.privateKey + "')";
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'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
});
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
I have 2 arrays in node js code
names = ['Name1','Name2','Name3','Name4', ...500 more items]
hashes = ['hash1','hash2','hash3','hash4', ...500 more items]
I have 2 columns in database table namely as 'Name' and 'hash'. I want to insert name and hash values in multiple rows simultaneously using only one mysql statement.
I tried to do it with one array. It executed successfully but its not working with 2 arrays. How should i do it ?
The Mysql insert query i wrote for one array is shown below:
var sql = "Insert IGNORE into lu (Name) VALUES ?";
con.query(sql,[array1],function(err, result){
if (err){
con.rollback(function(){
throw err;
});
}
});
You can just map names and hashes into one array - [["Name1", "hash1"], ...], then insert a nested array of elements.
var sql = "INSERT IGNORE INTO lu(Name, hash) VALUES ?";
var names = ['Name1','Name2','Name3','Name4'];
var hashes = ['hash1','hash2','hash3','hash4'];
var toOneArray = function(names, hashes) {
return names.map(function(name, i) {
return [name, hashes[i]]
});
}
con.query(sql, [toOneArray(names, hashes)], function(err, result) {
if (err) {
con.rollback(function(){
throw err;
});
}
});
I do not know if there is another way.