NodeJS + PostgreSQL: INSERT has more target columns than expressions - javascript

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.

Related

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!

Sql dynamic query syntax error

This is my sql query
"select * from applicant where email =ABC.Com"
I want table name, colum name and value after where clause dynamic in form of variables there. Can you tell me the right syntax? I have tried this so far
"select * from " tableNameVariable+"where "columnNameVariable+"= "inputedEmailVariable
now this query is giving an error near =inputedEmailVariable.
Note : I want to use this string in nodejs function. Please tell me right syntax?
Try:
"select * from " + tableNameVariable + " where " + columnNameVariable + " = '" + inputedEmailVariable + "'"
You're missing some + operators, and also missing a space before where.
var sql = "select * from " + tableNameVariable + " where " + columnNameVariable + " = " + inputedEmailVariable
You should be very careful if the variables are coming from user input, since this can result in SQL injection. Make sure the variables contain table and column values that they're allowed to access.
And if you're compareing the column with a string, you'll need quotes around the string. But it would be better to use a placeholder at that point, rather than concatenating the variable.

Javascript for while with mysql update when not having value

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

Pass multiple parameters in view when using a string to call a JS function in MVC3

I am calling a function with one parameter "modalXPTO.HtmlFieldPrefix" sucessfuly like this:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + modalXPTO.HtmlFieldPrefix + "')";
However, I would like to send more than one parameter, and I would expect this should work:
modalXPTO.AdditionalJavaScriptCallback = "myFunction('" + "{parentContainer:" + modalXPTO.ModalDivId + ", htmlFieldPrefix:" + modalXPTO.HtmlFieldPrefix + "}" + "')";
But it doesn't. Can anyone tell me what I am missing?
Here is the myFuntion declaration:
function myFunction(arg){
alert(arg.htmlFieldPrefix);
alert(arg.parentContainer);
}
I've fixed it.
modalXPTO.AdditionalJavaScriptCallback = "myFunction(" + "{parentContainer:'" + modalXPTO.ModalDivId + "', htmlFieldPrefix:'" + modalXPTO.HtmlFieldPrefix + "'}" + ")";
It is because of the misplaced "'". I wanted to pass an object with two parameters, but because of these characters I was passing a string instead.

Categories