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

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Passing variables in Redirect() without exposing them in the URL; a methodical approach

After scouring the depths of the internet, I have been on a quest to figure out how to seamlessly redirect to a new page on my site while discreetly passing a variable without exposing it in the URL like so: www.test.com/?variable=dont.want.this.here I a ...

What is the best way to showcase a collection of items using a table layout in JavaScript?

I am relatively new to React/JS programming and I'm struggling to understand why my code isn't working correctly. My goal is to create a column with rows based on the items in my Array, but only the header of the table is displaying. After looki ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

Generating dynamic variable names in JavaScript

Looking for a similar solution. var item_<?php echo $variable->n ?> = <?php echo '32' ?> Trying to achieve something like this: var item_342 = '32' ...

Combine PHP, jQuery, and AJAX to retrieve multiple values simultaneously

I have been using jQuery AJAX for my projects. When I make an AJAX call to a PHP page, it normally returns a single value to the success function of AJAX. However, I am now looking to retrieve multiple data individually. How can I achieve this? This is th ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Assistance required for activating an unidentified function or plugin within a Chrome extension

I am currently working on a project involving a chrome extension designed to automate tasks on a specific website. My main focus right now is trying to trigger the click event of a link that has an event handler set up through an anonymous function as show ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

I'm looking to use JavaScript to dynamically generate multiple tabs based on the selected option in a dropdown menu

I'm reaching out with this question because my search for a clear answer or method has come up empty. Here's what I need help with: I've set up a dropdown titled 'Number of Chassis'. Depending on the selection made in this dropdown ...

When trying to link a Redis microservice with NestJS, the application becomes unresponsive

I am attempting to create a basic hybrid app following the guidance provided by Nest's documentation, but I have run into an issue where the app becomes unresponsive without any errors being thrown. main.ts import { NestFactory } from '@nestjs/c ...

Repeated module imports

Currently, as part of my app development process, I am utilizing Parcel along with @material-ui/styles. One crucial aspect to note is that my app has a dependency on the @material-ui/styles package. Additionally, I have incorporated my own npm package, sto ...

Understanding the Flow of Parameters in Express Validator Functions

I am wondering about how the parameters are passed to the validator middleware. This snippet is extracted from express-validator. For instance, the parameter programming_language is passed to the check() function. const { check, oneOf, validationResult ...

Ways to prevent a particular link from functioning in HTML or JavaScript

Hey there, I am currently using a Gchat voice and video chat script. Check out my website if you're interested. The issue I'm facing is that someone logs into my chatroom and uses this flash link to crash other users' browsers. Whenever th ...

In Vue.js, when attempting to arrange an array of objects in descending order based on a specific key (such as "name"), the intention is to prioritize data containing uppercase letters to be displayed

I am struggling to organize an array of objects based on a specific key (name). My goal is to have the data with uppercase letters appear first, but for some reason, it's displaying the lowercase data first. I've been using the lodash method "ord ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

When a React component written in TypeScript attempts to access its state, the object becomes

Throughout my app, I've been consistently using a basic color class: const Color = { [...] cardBackground: '#f8f8f8', sidebarBackground: '#eeeeee', viewportBackground: '#D8D8D8', [...] } export defau ...

Tips for transmitting form information in a fetch call

As I was developing a nodejs server, I encountered an issue with the POST call that involves sending form input data to a remote server. Despite everything else working fine, the form data was not being received by the server. Below is the code snippet in ...

Adjust the values in a column using information from other columns

I'm currently developing a straightforward API using ExpressJS along with SQLite. As part of this project, I am implementing a router.patch method to update data entries in the database by utilizing the unique id as the primary key. Within the databa ...

AngularJS / Updating the URL only after the template's resolve property has been successfully resolved

Resolve plays a crucial role in preventing a template from being displayed based on certain conditional logic that deals with the result of a promise (whether it is solved or rejected). In my application, I implement it like this: .config(['$routePr ...