Using Express to pass a variable to MySQL

app.get('/sort', (req, res) => {
    var tabelle = req.params.table;
    let sql = "SELECT * FROM users ORDER BY tabelle DESC;";
    let query = connection.query(sql, (err, rows) => {
        if(err) throw err;
        res.render('user_index', {
            title: 'CRUD Operation using NodeJS / ExpressJS / MySQL',
            users: rows
        });
    });
});

In my CRUD application, I am trying to implement sorting functionality in MySQL based on the value of a variable called tabelle. However, I'm facing challenges in getting this to work effectively. The application is built using technologies like Node.js, Express, ejs, and MySQL.

Answer №1

Ensure to include a ? in your SQL query to protect against SQL injection attacks

let sql = "SELECT * FROM users ORDER BY ? DESC;";

let query = connection.query(sql, [table], function(err, results) {
    ...
});

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

Exploring Mongoose: A Guide to Populating Data from a Parent to a Child

I'm currently diving into the world of mongoose, where I have set up 3 collections (User, Post, Comment), each with its own unique schema: User { fullName: String, email: String, } Post { author: {type: mongoose.Schema.Types.ObjectId, required ...

Unable to import necessary modules within my React TypeScript project

I am currently building a React/Express application with TypeScript. While I'm not very familiar with it, I've decided to use it to expand my knowledge. However, I've encountered an issue when trying to import one component into another comp ...

Ways to abstract two comparable arrays in nodejs

I have two arrays with similar code structure, but only one parameter is different. I am looking to eliminate the redundancy and simplify the code by making it more general. Code : var record1 = "" var Data1 = { "@" : { "Version" : "some" } "transation" ...

The websocket server implemented in Node.js with the use of the "ws" library is exhibiting a peculiar behavior where it disconnects clients at random intervals,

My WebSocket server implementation is quite simple: const WebSocket = require('ws'); const wss = new WebSocket.Server( { server: server, path: "/ws" }); wss.on('connection', function connection(ws, req) { console.log("Connect ...

Error in node.js: 'arraystring' is not a defined variable

Currently, I am working on a project that involves demonstrating User Input Validation with JOI by validating Nested Objects and Arrays. However, an issue has arisen where the error message arraystring is not defined keeps popping up. How can I resolve th ...

Retrieve data from a MySQL database and input it into a PHP URL

I am having trouble retrieving a username from the database to fetch the corresponding JSON data for that user. The current code I have implemented is generating a 500 error, possibly due to some issue with $json variable... Could someone offer assistance ...

Important: Express 4 and Passport Issue with Session Creation

So far, I have managed to successfully log users in using Facebook. However, once I retrieve the information from Facebook, it seems to get lost. I'm not sure if I should be responsible for creating the session or if there is something crucial that I ...

Issue with NPM Installation - Microsoft SQL Server Driver

Attempting to set up msnodesql using npm, a library for sql server drivers, on my Windows Server 2012 machine. I've successfully installed Visual C++ 2010, node-gyp, and Python 2.7.x.x as prerequisites. However, when I try running npm install msnode ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

using an array as an argument in an express POST request

I am currently exploring express-validator, and I came across a specific example in the documentation that caught my attention. The example code snippet is as follows: const { check, validationResult } = require('express-validator/check'); app. ...

`vue-template-compiler package.json module not found in each new project``

After transitioning from Linux to Windows and setting up a programming environment, I encountered an issue that I didn't remember facing on Linux. Here are the steps I took: 1. Installed Node.js 2. Ran npm install -g @vue/cli for CLI installation 3. C ...

Is there a way to set up the application that consumes an npm module with a private git url to strictly utilize files exclusively from the module's dist folder?

In my angular application, I encountered an issue with angular-cli not supporting the creation of a library. To work around this, I opted to use the popular git project found at https://github.com/jvandemo/generator-angular2-library for creating my library ...

Error: Callback function in Mongoose Populate is returning undefined

I have a query set up in MongoDB where I am trying to display all subcollections of the schema while excluding the account ID. The issue is that I am getting "undefined" as the result for the callback "list_data". Here is how my query looks in my routes: ...

Issue with PHP query not functioning correctly when variables are utilized

I encountered a strange issue with my SQL query. Initially, this query worked perfectly fine: $query = "SELECT * from hired WHERE username = 'kaas' and dvd = 'dvd 2'; However, when I modified it to use session and post variables like b ...

Locate using the category title or create an additional table

My database contains a list of website addresses, each categorized with plain English categories such as movies, tutorials, etc. The table includes fields for site_id, site_url, and site_category. I am debating between keeping it in one table or splitting ...

What is the best way to send the UserId from a payment API endpoint to a webhook endpoint?

insert image description hereI am currently integrating Firebase for user registration and authentication purposes. Additionally, I am incorporating the use of Stripe CLI in my project workflow. One specific requirement is to trigger certain events only fo ...

Warning: Outdated version detected during NestJS installation on npm

Whenever I attempt to download NestJS using the command npm i -g @nestjs/cli, I encounter the following issue: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d5c9d3d4c5c3cb8ed7cbc1ccdcdffccdc3d0"><?[ ...

Dealing with the challenges posed by middleware such as cookie access and memory leaks

Utilizing express with cookieParser() where my client possesses the cookie named: App.Debug.SourceMaps. I've crafted a middleware as follows: app.get('/embed/*/scripts/bundle-*.js', function(req, res, next) { if (req.cookies['App ...

What causes this unexpected npm error to occur while trying to install dependencies?

While attempting to install project dependencies through npm, I encountered the following error message: npm ERR! code ENETUNREACH npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/tslib/-/tslib-2.0.0.tgz failed, reas ...

Is it possible to integrate Wavify with React for a seamless user experience?

For my website designs, I have been experimenting with a JavaScript library known as Wavify (https://github.com/peacepostman/wavify) to incorporate wave animations. Recently delving into the world of React, I pondered whether I could integrate Wavify into ...