Any suggestions on MySQL auto-inserted apostrophes?

Having trouble updating a value in my Database, as it's resulting in an error.

Backend:

router.patch("/toggleState", (req, res) => {
const todoId = req.body.todoId;
const attribute = req.body.attribute;
const newValue = req.body.newValue;
const sql = "UPDATE posts SET ? = ? WHERE todo_id = ?";

db.query(sql, [attribute, newValue, todoId], (err, result) => {
    if (err) throw err;
    res.send(result);
});
});

    

Frontend:

const toggleState = (todo_id, attribute, newValue) => {
    if (userId) {
        console.log("ATTRIBUTE: ", attribute);
        //Axios.patch(`${apiUrl}/todo/toggleState`, { todoId: todo_id, attribute: attribute, newValue: newValue });
    }
    dispatch({ type: actionTypes.toggleState, payload: { todo_id, attribute } });
};

Error: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''important' = 1 WHERE todo_id = 1' at line 1"

After SQL processing: sql: "UPDATE posts SET 'important' = 1 WHERE todo_id = 1"

Noticing that there are ' ' apostrophes surrounding my attribute variable (important), which seems to be causing the error. Although, I've checked the variable both in the frontend and backend console logs, and it's of type string without any apostrophes. Any ideas?

Also, when attempting the same SQL string in mysql-workbench with real values instead of variables, it works fine.

Running react/axios on the frontend and Node/Express with MySQL on the backend.

Answer №1

One way to quickly solve this issue is by utilizing ?? as the column name. However, it's important to note that dynamically inserting column names during the preparation of a statement is generally not recommended, hence the need for this workaround. This precautionary measure helps to prevent SQL injection attacks where a user may try to inject a manipulated query to alter random columns. A more robust solution involves selecting a query string based on the attribute and automating this process by searching for the provided attribute in an array of queries.

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

Having issues with inserting data in MySQL database

I am facing an issue with a file containing 50000 rows. Despite having a code in place, it seems to be skipping several rows and pages. When I check in phpmyadmin, the data appears like this: 1-10, then jumps to 23-34, 78, 102, 345, 546, and so on. I sus ...

The system cannot locate the "default" task. Please consider using the --force option to proceed. The process has been halted due to warnings

Below is the content of my gruntfile.js file var fs = require("fs"), browserify = require("browserify"), pkg = require("./package.json"); module.exports = function(grunt) { grunt.initConfig({ mochaTest: { test: { options: { ...

Set up a WhatsApp web bot on the Heroku platform

I am currently in the process of developing a WhatsApp bot using the node library whatsapp-web.js. Once I finish writing the script, it appears something like this (I have provided an overview of the original script) - index.js const {Client, LocalAuth, M ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

How to eliminate looping animations with jQuery

While looping through items, I am encountering an issue where an animation triggers when the loop returns to the first div. I simply need a way to switch between divs without any animations on a set interval. $(document).ready(function () { function s ...

Is it within the realm of possibility for a route-handling function to accept more than two parameters?

Recently, I started learning about node js and delved into the world of jwt authentication. While going through some code snippets, I came across a request handler in express that caught my attention. app.post('/login',function(req,res){...}); ...

Error: The SpringBoot API returned a SyntaxError because an unexpected token < was found at the beginning of the JSON response

I am currently following a tutorial on Spring Boot React CRUD operations which can be found here. However, I have encountered an issue when trying to fetch JSON data from the REST API and display it in my project. Despite following the steps outlined in th ...

What is the procedure to incorporate login credentials into the source of an iframe?

Is there a way to pass user auto login in the src URL? <iframe src="https://secure.aws.XXX.com/app/share/28228b0ccf0a987" width="1060px" height="1100px"></iframe> I attempted to achieve this, but it still shows the login screen <ifr ...

Adding a dynamic form to each row in a table: A step-by-step guide

https://i.sstatic.net/HctnU.jpg Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

JavaScript incorporates input range sliding, causing a freeze when the mouse slides rapidly

Currently working on a custom slider and encountering an issue. When quickly moving the mouse outside the slider's range horizontally, exceeding its width, the slider doesn't smoothly transition to minimum or maximum values. Instead, there seems ...

What is the best way to position a single element in React using the Grid Component without causing any overlap?

I am struggling with positioning 3 components on my react page: PageHeader, SideMenu & FeatureList (which consists of Display Cards). Here is the code for each component: App.js // App.js code here... PageHeader.js // PageHeader.js code here... SideMenu ...

Automate the installation of an npm package while including the --save-dev flag

There is a lesser-known trick where npm can be utilized as a Node.js module to execute commands within the code. I am looking to gather user input on which packages are needed, install them programmatically while also saving them to the package with the - ...

retrieve the date value of Focus+Context by using the Brushing Chart

Currently, I am engaged in analyzing the sentiment of tweets on Twitter. The analysis will produce an overall area graph that allows me to choose a specific date range and extract all or some of the tweets falling within that range. In order to create a t ...

Querying Mongoose Nested Data in Express: A Comprehensive Guide

I need to retrieve the "stocked" boolean value for item "4" belonging to user "456" from my mongoose data collection. However, when I try to query for this specific information, I end up receiving the entire user object instead. Data: data = [{ use ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...

What could be causing MS browsers to transform my object array into an array of arrays?

Noticing an interesting behavior with Microsoft browsers especially when dealing with data returned from our product API. It seems that the array of 52 product objects is being transformed into several arrays, each containing only 10 objects. Our error tr ...

encountering a loading issue with angular2-modal in rc1 version

Currently, I am implementing a library called angular2-modal. This library offers various modal options including bootstrap and vex for angular 2. While vex is functioning properly, I encounter an error when switching to bootstrap: responsive-applicati ...

SQL: Group by - identify the attribute with the highest quantity

I'm new to SQL and I have encountered the following issue: Here is a sample of my table data: name city people -----|-----|--------| John | A | 5 | Ben | D | 6 | John | A | 5 | Ben | A | 5 | John | B | 8 | ...

A step-by-step guide to showing images in React using a JSON URL array

I successfully transformed a JSON endpoint into a JavaScript array and have iterated through it to extract the required key values. While most of them are text values, one of them is an image that only displays the URL link. I attempted to iterate through ...