Inserting data into a table using variables in Mssql database management system

I'm really struggling to find a way to safely add my Variables into an MSSQL server.

I've tried everything. Could someone please help me and provide the solution for adding my Variables into the Database?

It is crucial that I prevent any possibility of SQL-injection.

app.post('/addUser', addUser)

async function addUser(req, res) {
    let pool;

    const bodylength = req.body.length;
    console.log(bodylength)

    for (let index = 0; index < bodylength; index++) {

        const id = req.body[index].id;
        const first_name = req.body[index].first_name;
        const last_name = req.body[index].last_name;
        const active = switchToBool(req.body[index].active);


        console.log(id, first_name, last_name, active)

        try {

            pool = await sql.connect(config);
            const request = pool.request();

            request.input('id', sql.Int, id)
            request.input('first_name', sql.VarChar(50), first_name);
            request.input('last_name', sql.VarChar(50), last_name);
            request.input('active', sql.Bit, active);

            request.query(`INSERT INTO test (Id, first_name, last_name, active) VALUES (id,first_name,last_name,active)`)

        } catch (error) {
            return res.status(500).send(error)
        }
        res.status(200)
    }
}

Regardless of what I attempt, I keep encountering a 500 error or UnhandledPromiseRejectionWarning: RequestError: Invalid column name 'active'.

Answer №1

Typically, this code snippet should be useful for the task at hand:

...
request.query("INSERT INTO database_table (ID, name, age) VALUES ?", [id, name, age])
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to temporarily turn off Backbone.sync for a fresh model and then reactivate it once the user clicks the save button

I am currently working with a Backbone collection model that consists of sub-models as elements, along with views to edit it. My objective is to have the syncing functionality "turned off" initially when the model is created, so that the back end is not c ...

Is it possible to make a field optional in express-validator if a certain condition is met by using .if(myCondition).optional()?

I am currently utilizing the express-validator package and I am interested in combining the 'if' and 'optional' functions. Here is an example of what I would like to achieve: Let's assume that config.requireFieldAB = false await b ...

Ways to guarantee a distinct identifier for every object that derives from a prototype in JavaScript

My JavaScript constructor looks like this: var BaseThing = function() { this.id = generateGuid(); } When a new BaseThing is created, the ID is unique each time. var thingOne = new BaseThing(); var thingTwo = new BaseThing(); console.log(thingOne.id == ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Encountering a 404 error for core.js and browser.js while loading an Angular 2 app through system.src.js

I am new to Angular2 and have followed the Angular2 quickstart and tutorial to get started. Just to provide some context, when a user clicks on a link in the top navigation bar of my webapp, it triggers a server side request. The resulting page returned t ...

The variable is constantly reverting back to its initial value

Here is the code snippet: function send() { var nop = 6; var send_this = { nop: nop }; $.ajax({ type: "GET", data: send_this, url: "example.com", success: function(r) { ...

Tips on integrating discretionary authentication in React/Express application?

I'm currently working on a self-hosted bookmarks manager application that utilizes React on the frontend and Express on the backend. While I have successfully implemented a standard authentication system using JWT, I am now considering making authenti ...

Exploring the capabilities of AngularJS directives through ng-html2js testing

Many questions have been raised about the ng-html2js plugin, but unfortunately, none of the answers provided were able to solve my specific issue. I meticulously followed the official installation guide and also referenced the example available at https:/ ...

Copy the contents of matrixA into matrixB and append a new element to each array within matrixB

I want to copy the values from matrixA into matrixB and then add a new element to each array in matrixB. let number = 100; matrixA = [ [1, 2], [3, 4] ]; matrixB = [ [1, 2, 100], [3, 4, 100] ]; Currently, my code looks like this: for (let ...

Is it possible to use vanilla JavaScript scroll event with AngularJS framework?

I am attempting to track the window offset from the top of the document, but I am facing issues with jQuery scroll functionality. Can a vanilla JavaScript scroll event listener be used effectively within an Angular environment? app.directive('owlCaro ...

Tips for managing an interval for play, pause, and stop functions in JavaScript or Node.js

In my main file, I have an API to control the playback of a video. main.js const { mainModule } = require('process'); const { startVideo, pauseVideo, stopVideo } = require('./modules/video.js'); function init(payload) { if(payl ...

Utilizing HTML and JavaScript to Download Images from a Web Browser

I'm interested in adding a feature that allows users to save an image (svg) from a webpage onto their local machine, but I'm not sure how to go about doing this. I know it can be done with canvas, but I'm unsure about regular images. Here i ...

Tips for implementing personalized command buttons in Kendo Grid with AJAX request utilizing JavaScript

I am struggling with implementing custom command buttons in a Kendo grid that makes an AJAX call using JavaScript to call a web API post action with dynamic parameters (start, stop, restart) behind button clicks. datasource dataSource = new ken ...

Using an iframe to access HTTP content from an HTTPS website

Currently, I am facing an issue with a page that contains an iframe loading an HTML template from an Amazon AWS S3 bucket. Within the iframe, my goal is to take the link of the parent window and add additional parameters. For example, let's say my pa ...

Execute a function singularly upon vertical scrolling upwards or downwards

Looking for a solution to load two distinct animated graphics on a website when scrolling up or down, I managed to trigger the desired functions. However, there seems to be a bug where the functions are being triggered excessively: $(window).scroll(func ...

Is it acceptable to initiate an import with a forward slash when importing from the root directory in Next.js?

I've noticed that this import works without any issues, but I couldn't find official documentation confirming its validity: // instead of using a complex nested import like this import { myUtil } from '../../../../../lib/utils' // this ...

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

Is it possible to update table cell content depending on selected option?

Displayed here is the select block: <form> <select id="select"> <option disabled selected value="choose"> CHOOSE </option> <option value="i2g" id="i ...

Strategies to verify if two objects of the same class possess the same attribute

I have multiple elements with the same class and unique attribute values, such as: <div class="myclass" data-attr="1"></div> <div class="myclass" data-attr="2"></div> <div class="myclass" data-attr="3"></div> <div cl ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...