What is the best way to incorporate a table name into a MySQL query using ExpressJs?

My goal is to retrieve the contents of a specific table using this code snippet:

let tableName = req.body.login
connection.query('SELECT * FROM ?', tableName, (err, rows) => {
    if (err) throw err
    res.send(rows)
})

However, as tableName is a string, it ends up being inserted into the query with quotes, leading to an error. If this approach isn't feasible, what database structure would allow me to add users and additional data to any chosen table?

Answer №1

To include the table name in a raw SQL query, you simply need to reference it before calling the query method. Here's an example:

let tablename = req.body.login;
let rawQuery = 'SELECT * FROM ' + tablename;
connection.query(rawQuery, (err, rows) => {
    if (err) throw err
    res.send(rows)
})

I hope this explanation proves useful.

Answer №2

One easy solution is to utilize the power of template literals.

By using backticks `

let tablename = req.body.login
connection.query(`SELECT * FROM ${tablename}`, (err, rows) => {
    if (err) throw err
    res.send(rows)
})

Alternatively, you can simplify the code even further:

connection.query(`SELECT * FROM ${req.body.login}`, (err, rows) => {
    if (err) throw err
    res.send(rows)
})

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

PHP form with multiple conditional statements

Looking for assistance with my website's "subscribe" form validation before submitting entries. Below is the form code that requires completion. Form code <div class="col-lg-8 col-md-12 col-sm-12 col-xs-12"> <h1> Subscribe ...

Uniqueness arises from the interchangeability of values between columns

I am currently facing a query issue that needs to be resolved: select distinct v.npi1, v.npi2, count(*) from hcpc cross join lateral (values (f_rend, f_bill), (f_rend, t_rend), (f_rend, t_bill), (f_bill, t_rend), (f_bill, t_bill), (t_rend, t_bi ...

Why does the useEffect() from before continue to run for a long period after the component has already been rendered?

At the moment, my ReactJs code looks like this as I work on implementing a stopwatch: const App: React.FC = () => { const [seconds, setSeconds] = useState(0); const [isPaused, setIsPaused] = useState(false); const secondsToTimerFormat = (seconds: ...

Issue with ExpressJS serving static templates by using app.use

Trying to display a form as a static page using ExpressJS via app.use is resulting in an error. const express = require('express'); var app = express(); app.use(express.static(__dirname + 'public')); app.listen(3000); Folder structure ...

Encountering an error while transmitting variables through ajax

Encountering an issue when attempting to remove a user from the database. Below is the code I have written: On the server side: @RestController public class EmployeeRestController { @DeleteMapping( value = "/delete_user") public List<Em ...

Implementing Icons in Custom Headers of AG Grid Using vue js

I am working on implementing a new feature in AG Grid where I want to display an info icon in the header along with a tooltip that appears when the icon is hovered over. I have already created a custom tooltip component that works correctly, but once I a ...

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

Pattern for identifying text that exclusively consists of whitespace characters and `<br>` tags

Here is an example of a string: <br /> <br /> <br /> Sometimes the string can look like this: <br /> <br /> Or simply like this: & ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...

Tips for Showing Certain Slides When the Page Loads

When using jQuery filter effects to organize div slides on a page, I encountered an issue where all the divs containing different slides are displayed on page load instead of just the default chosen ['active'] div. The filter effect itself is fun ...

Getting parameters from a URL with a React frontend and Express backend: A step-by-step guide

I am currently developing a react application with an express backend. I am in the process of integrating socket io chat functionality into the frontend. Everything is functioning properly, but I am now looking to extract parameters from the URL in order t ...

EmeraldSocks Tweenmax motion design

I need help with Tweenmax animation. I'm attempting to animate an id selector, but nothing is happening. Both the selector and content are unresponsive. Can someone assist me? Here is the code: <!DOCTYPE html> <html> <head> ...

Selecting a HEX code from a color picker to configure three.js as a string

Recently, I've been using a color picker from jscolor.com that outputs colors in the format of FFA6A6. The challenge I'm facing is integrating this color output with three.js, which requires the color to be in the format of 0xFFA6A6. As much as I ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

The Javascript array contains information, but its length is currently empty

UPDATE: It seems that I misunderstood how promises work, leading to a synchronization issue. I mistakenly assumed that ".then" waits for the promise to resolve, which is not the case. An unusual error has cropped up that has me stumped. I'm puzzled ...

Confirming the Checkbox Field - ASP.NET with the Power of jQuery

I am currently working on a straightforward validation process for checking agreements using an asp:checkbox and an asp:button click. When the button is clicked, I have this function being called: OnClientClick="ValidateConditions();" The function itsel ...

Tips on dividing the information in AngularJS

Sample JS code: $scope.data={"0.19", "C:0.13", "C:0.196|D:0.23"} .filter('formatData', function () { return function (input) { if (input.indexOf(":") != -1) { var output = input .split ...

How do you update the bind value in VueJs when using :value="text"?

My attempts at updating a string when the content is changed inside a textarea are not successful. Vue component: <template> <div> <textarea :value="text" @change="changed = true" @keyup="changed = true"&g ...