Javascript for while with mysql update when not having value - javascript

I will Update a Value in my Database when this is not setted.
I have this Code:
items.forEach(function(item,i,arr){
mysqlConnection.query('UPDATE `SkinBank` SET `AssetID`=\'' + item.assetid + '\', `Status`=\'market\' WHERE `Status`=\'open\' AND `Tradeoffer` = \'' + offer.id + '\' AND `SkinName` = \'' + item.market_hash_name + '\'', function (err, row, fields) {});
});
When i put than 2 "Items" which has item.assetid (like: Item 1 has = 123123 and Items 2 has= 987987) than all two items who has nothing get the same Assetid value like 123123 or 987987.
How i can make, that he gives every item ONE AssetId.
Before this, the column "AssetID" has nothing in there

I'm guessing that your WHERE clause is matching too many rows. It's not clear what library you are using, but if you are using node-mysql you can output the number of rows updated in the callback function:
connection.query('UPDATE `SkinBank` SET `AssetID`=\'' + item.assetid + '\', `Status`=\'market\' WHERE `Status`=\'open\' AND `Tradeoffer` = \'' + offer.id + '\' AND `SkinName` = \'' + item.market_hash_name + '\'', function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
})
https://github.com/felixge/node-mysql#getting-the-number-of-changed-rows

Related

EJS recieve json containing code as string

Im sending a stringified json that should have property:
recievedObject: {"code":"this is a code snippet"}
(the code property has no specified programming language)
and then parsing it like this:
var items = JSON.parse('<%- JSON.stringify(items) %>')
When I try to parse the stringified json I received I get parsing errors (im guessing its because of the code string often containing characters like " ', line breaks etc.)
Is there a way to bypass or get around this problem without changing the string in any way? (I was able to get this working after encrypting it, but I would prefer not to do this)
example of how the code string might look:
code: "router.get('/', function(req, res, next) {\n" +
' try {\n' +
' const cities = spreadsheet.getData()\n' +
'\n' +
' } catch(err) {\n' +
' console.log(err)\n' +
' }\n' +
'\n' +
" res.render('index', { cities: cities})\n" +
'})'

How to pass a question mark express router api to update sql

I want to update a varchar field (String) using and End-Point Api (Express NodeJS) but I have problem went I pass invalid inputs like question mark.
Express End-Point:
router.get("/updateField/:table/:field/:value/:num/:postid/", function(req, res) {
connection.query(
'UPDATE '+ req.params.table +' SET ' + req.params.field +' = '+JSON.stringify(req.params.value) +' where language ='+ req.params.num +' and post_id ='+req.params.postid
This code work fine:
http://localhost:3001/api/updateField/posts/TITLE/When/1/1
But this NOT WORK:
http://localhost:3001/api/updateField/posts/TITLE/When?/1/1
I send the request from react like this:
fetch(
"http://localhost:3001/api/updateField/" +
table +
"/" +
field +
"/" +
value +
"/" +
lenguage +
"/" +
post_id
);
Use javascript function encodeURIComponent() to escape special characters in URL parameters.
For example try this on your browser console and you'll get an idea:
console.log(
"http://localhost:3001/api/updateField/" +
table +
"/" +
field +
"/" +
encodeURIComponent(value) +
"/" +
lenguage +
"/" +
post_id
);
console.log(encodeURIComponent("When?"));
You will see that "When?" is replaced with "When%3F" in URL.
In Node.Js, you'll receive parameter value as string "When?".
To know more about encodeURIComponent(), refer to this

JavaScript sql result row, using a property that has parenthesis in its name

I am trying to do nested queries in order to insert into a table based apon an earlier select statement. However I am running into trouble because my first select statement selects and AVG() of a row. I have not been able to find a way to get the result row object that I have to select the property 'AVG(row)' instead of the trying to call .AVG() on something. The code is below and any help would be appreciated.
var sql1 = 'SELECT tropename, AVG(criticScore) FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
//console.log(sql1)
con.query(sql1, function (err1, result1) {
if (err1) throw err1;
Object.keys(result1).forEach(function(key) {
var row2 = result1[key];
var trope2 = row.tropeName;
console.log(trope2)
var avgScore = row.AVG(criticScore)
console.log(avgScore)
sql = 'INSERT INTO TropesWithAverageScores (tropeName, criticScore) VALUES (' + trope2 + ',' + '\'' + avgScore + ')';
///console.log(sql)
con.query(sql, function (err, result) {
if (err) {}
});
});
});
Fixed it myself,
first, I was getting the attribute on row, not row2 object.
Secondly I simplified it by aliasing my first select state, so it now reads
SELECT tropename, AVG(criticScore) as avgCS FROM tropesWithScore where tropeName = '+ '\'' + trope + '\'';
Hope this helps someone else!

NodeJS + PostgreSQL: INSERT has more target columns than expressions

I'd like to INSERT the current timestamp with CURRENT_TIMESTAMPon each new user registration. The column number equal the number of parameters in VALUES. Yet I get INSERT has more target columns than expressions. Using the node-postgres npm module as a controller.
//Just 3 parameters, timestamp is hardcoded in the query
exports.create = function (username, email, password) {
DB.connect(connection, function (err, client, done) {
var query = client.query(
//4 columns
"INSERT INTO users (username, email, userpass, datecreated) VALUES" +
//4 parameters
"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "'" + "'CURRENT_TIMESTAMP')");
query.on('error', function (error) {
console.log("query returned an " + error);
});
query.on('row', function (row, result) {
result.addRow(row);
});
});
};
Missing comma after password and no tics around current_Timestamp
"INSERT INTO users (username, email, userpass, datecreated) VALUES" +
//4 parameters
"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "," + "'CURRENT_TIMESTAMP)"
--- While this may have been the accepted answer addressing the immediate issue, I highly recommend Craig and Lars answers be evaluated. Use of Parameters is a far better long term approach as it is more secure; actually easier to code once you understand how, and the correct modern paradigm.
My previous answer was based on older provided code, it isn't accurate anymore so I removed it.
You're missing a comma , between password and CURRENT_TIMESTAMP.
I'd advise you to use parameterized queries instead of building them yourself like this.
`"(" + "'" + username + "'" + "," + "'" + email + "'" + "," + "'" + password + "'" + "'CURRENT_TIMESTAMP')"`
Nonononono!
That is not how you pass parameters, and may bewhy you're having problems. (xQbert points out you're also missing a comma).
Imagine if I entered the username
');--DROP TABLE users;--
Splat. There goes your application.
Use parameterized queries by binding parameters to placeholders. This is often called "prepared statements" though they're really something different.
e.g.
client.query(
"INSERT INTO users (username, email, userpass, datecreated) VALUES ($1, $2, $3, current_timestamp)",
[username, email, password])
Your problem will go away.
Now read this.
Note that this isn't just a security problem, it's also a bug that will cause errors even from non-malicious users. I enter a nice secure looking password like 94/Ql#$'B'wC. Boom, your app falls over with a database error.

Why a reference to object is replaced with its value

I use node.js and express.
I saved on the 'req.session' a complex object that includes array of objects.
In addition I save reference to one of the objects in the array.
For example:
var value = {
name: "name"
, values: []
};
req.session.value = value;
//
// I populate 'req.session.value' with values (with the same structure)
//
// then I save reference to one of the inner objects
var currentValue = req.session.value[3];
//
// later I try to change the save object
//
currentValue.name = "newName";
I expected that if I change the 'currentValue' then the 'req.session.value[3]' will be changed as well. However, for some reason it doesn't happen.
To be concrete, if I change the currentValue immediately after I assign it then the req.session.value[3] is changed but if I am doing it in the next call then just the currentValue is changed.
In the example: I do the assignments to the 'req.session' in the "app.get(...)" if I change the value of the currentValue in the "app.get(...)" it is run ok (the value change in both places) but if I change it in the 'app.post(...)' the only object that change is the currentValue while the req.session.value[3] left the same.
Thanks in advance,
Shai
The code:
'app.get("/template/:templateid/feature/add", isTemplate, function(req, res) {'
' if (!req.session.features) { // if features empty'
''
' // Save the first features level from the current template in the session '
' req.session.features = req.session.template.feature;'
' //'
' if (!req.session.featureNodes) { // featureNotes is a stack/branch of the features'
' req.session.featureNodes = [];'
' }'
' if (!req.query.featureroot || req.query.featureroot == "") {'
' } else {'
' var featureRoot = getFeature(req.query.featureroot, req.session.features); // get one object from req.session.features'
' if (featureRoot) {'
' req.session.featureNodes.push(featureRoot); // save reference'
' var featureR = req.session.featureNodes.pop(); // do check that work!'
' var values = {'
' name: "req.body.name"'
' , description: "req.body.description"'
' , wieght: "req.body.wieght"'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
''
' featureR.feature.push(values); // also req.session.features changed'
' req.session.featureNodes.push(featureRoot); // push the reference back for use later'
' } '
' }'
' res.render("addfeature2template.jade", { '
' title: "Add new feature"'
' ,template: req.session.template'
' ,feature: req.session.featureNodes'
' });'
'});'
''
'app.post("/feature/add", isUser, function(req, res) {'
' var SUBMIT = "Create";'
' var CANCEL = "Cancel";'
' switch ( req.param("feature") ) {'
' case SUBMIT:'
' var fields = { name: 1, description: 1, wieght: 1};'
' var values = {'
' name: req.body.name'
' , description: req.body.description'
' , wieght: req.body.wieght'
' , created: new Date()'
' , modified: new Date()'
' , feature: []'
' };'
' if (req.session.featureNodes.length < 1) {'
' req.session.features.push(values);'
' } else {'
' var featureRoot = req.session.featureNodes.pop(); // pop the reference'
' featureRoot.feature.push(values); // change the object but the req.session.features didnt changed '
' }'
' req.session.template = template;'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' case CANCEL:'
' res.redirect("/template/" + req.body.templateid);'
' break;'
' }'
'});'
req.session object is serialized (to store) between the requests.
Example:
Request 1:
req.session = {};
var a = { hello : 'world' };
var b = a;
req.session.a = a;
req.session.b = b;
In this context variables a, b, req.session.a, req.session.b points to one object. You can change field hello in any of these objects, and this will to change in each of them.
After end of request req.session object will be serialized for session storage (memcached, mongodb, etc).
Request 2:
Before request 2 req.session object will be deserialized from storage. Now it contains plain values without references. You can access req.session.a and req.session.b but now it two different objects.

Categories