Home > OS >  only insert variables which have values, not undefined node.js
only insert variables which have values, not undefined node.js

Time:11-02

So i have this:

var dates = {
    monday: req.body.monday,
    tuesday: req.body.tuesday,
    wednesday: req.body.wednesday,
    thursday: req.body.thursday,
    friday: req.body.friday,
    saturday: req.body.saturday,
    sunday: req.body.sunday
}

    console.log(Object.values(dates))

the way this works is you can select a checkbox on the front end, and all the results will be sent to the backend regardless if you checked it or not. Now, i need to sort through those results to only insert the ones that were selected (they don't have defined values, like the array response below).

in the for loop result set, i it gets returned as so:

    [
  '2',       undefined,
  undefined, undefined,
  undefined, undefined,
  '1'
    ]

as you can see, 5/7 are undefined. So i have a standard insert query into SQL, but i need to insert only the values that are defined. so in my head i am thinking insert into clients where Object.values(dates) != undefined, but i know thats not right, especially cause that's now the way the sql query works lol.

I have this:

var addclient = "insert into clients (NAME, EMAIL, PHONE_NUMBER, TRAINER_NAME, HOUR, MINUTE, DATES) values ('"   name   "', '"   email   "', '"   phonenumber   "', '"   req.session.username   "', '"   hour   "', '"   minute   "', '"   dates   "')";

how can i do this?

CodePudding user response:

Besides the actual question, using unsanitzed input to create a sql string in the way it is shown in the snippet is a huge risk. It allows an attacker to perform a sql injection. See more here: https://owasp.org/www-community/attacks/SQL_Injection

CodePudding user response:

If you're hoping to insert the values as a comma delineated string, you can accomplish that by doing the following:

const formattedString = Object.values(dates).filter(el => el).join(', ');
var addclient = "insert into clients (NAME, EMAIL, PHONE_NUMBER, TRAINER_NAME, HOUR, MINUTE, DATES) values ('"   name   "', '"   email   "', '"   phonenumber   "', '"   req.session.username   "', '"   hour   "', '"   minute   "', '"   formattedString   "')";

Notice that I changed the "dates" in your insert method to the new "formattedString". Given your example, formattedString would be "2, 1".

  • Related