What is the best way to incorporate single quotes within a string literal in JavaScript when constructing SQL queries?

Currently, I am developing a SQL query using Javascript where I pass values. If any value is undefined, I want it to be passed as null. This is how my code looks:

const sql = `INSERT INTO MYTABLE(
  COLUMN1,
  COLUMN2
)
VALUES(
  ${param.value1 ?? null},
  ${param.value2 ?? null}
)`;

Although the null check functions correctly, the database rejects values that are defined because they are not enclosed in single quotes. For example:

INSERT INTO MYTABLE(
  COLUMN1,
  COLUMN2
)
VALUES(
  test,
  null
)

The database requires me to wrap test in single quotes like 'test'. However, I am struggling to find an effortless method to achieve this. How can I automatically add single quotes around my values if they are not undefined?

Thank you.

Answer №1

Make sure to include single quotes outside of the ${}, like this: '${}'

This approach could potentially lead to complications as 'null' should be interpreted as null value, not a string 'null'

Have you considered converting your query into a function with switch statement? How many columns are you looking to fill in? You've shown two here, but are there more?

let param = {
  value1: 'test'
}
let sql = `INSERT INTO MYTABLE(
  COLUMN1,
  COLUMN2
)
VALUES(
  '${param.value1 ?? null}',
  '${param.value2 ?? null}'
)`;
console.log(sql);

sql = sql.replaceAll("'null'", "null");

console.log(sql);

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

Insert half a million records into a database table using JavaScript seamlessly without causing the webpage to crash

I am facing an issue with my report system where running a single report query results in over 500,000 rows being returned. The process of retrieving the data via AJAX takes some time, but the real problem arises when the browser freezes while adding the H ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

The querySelector function seems to be identifying the element with the ID "submit" and another input element of type "submit"

My code includes a function that toggles between two elements' style.display values, switching them from "none" to "block" and vice versa. However, I've encountered an unexpected issue where the behavior of the "send" button seems to be linked wi ...

Learn how to efficiently insert images into a div element and then upload them to a server using AngularJs

I am currently working on developing a CRM application and have successfully integrated a feature that allows users to select a div from a range of options. There is a button provided to insert an image into the selected div, along with ng-style to define ...

Combining the powers of P5.js and Three.js to create a dynamic ThreeJS scene infused with captivating animations sourced from the P5.js library

Before we get started, I recommend checking out my previous post that inspired this question: https://i.sstatic.net/f7rck.png Drawing/Rendering 3D objects with epicycles and fourier transformations [Animation] Background: By using the P5.js library and ...

Tips for incorporating user-entered data from a text box into a JavaScript function and utilizing a loop

Although my code is functioning correctly, I am looking to make some adjustments but seem to be struggling to achieve the desired outcome. Essentially, I have two labels and an input field in which the user is prompted to enter a specific number of weeks ...

Exploring the possibilities of PHP, AJAX, and JSON

I am currently exploring the functionalities of ajax and json. Within my page named addAccount.php, I have a FORM containing the following INPUT elements: <input type="text" id="partnerCode" /> <input type="button" id="pCodeSearch" value="Sear ...

The correlation of types between function parameters using function overloads in TypeScript

In the process of developing a factory function, I am incorporating a type argument to specify the type of object being created, along with a parameter argument containing parameters that describe the object. The parameters are dependent on the specific ty ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

Send a PUT request using Ajax

I am a beginner when it comes to Ajax requests and I have crafted the code shared in this Pastie. On line 107, my $.PUT function is causing an error in Firebug stating that $.PUT is not a recognized function. I acknowledge that there are issues with my aja ...

What is the best way to create an associative array using jQuery and then send it through AJAX to be parsed by PHP?

Is there a way to create an associative array in jQuery and send it via ajax to a php page for processing? Here is an example of what I am trying to achieve... // jQuery if($something == true) { data[alt] = $(this).attr('alt'); data[sr ...

Guide on Loading and Implementing Fonts from a Self-Hosted Server in a React Application using MUI

I'm currently developing a React application with the MUI library and encountering an issue related to dynamically setting the font-family. The main objective is to provide users with the option to choose a font from a configurator, where fonts are ho ...

A Sweet Alert to Deliver your Morning Toasty Message

I seem to be encountering an issue with my toast message. Instead of the toast popping up immediately after submitting the form, it keeps appearing even if I haven't submitted the form and even when navigating from another page to this one, the toast ...

Poor initial placement of the Dialogs when the content exceeds the space available

While using material-ui^0.20 with react^16.2, I encountered an issue when initially displaying a Dialog containing a Component with excessive content. The problem is illustrated in this image: https://i.sstatic.net/RF8Mu.png This is the expected appeara ...

Does the round function always produce the most accurate floating point approximation?

Will the result of using round(3.12143345454353,2) always be equivalent to simply using the literal value 3.12? The floating point approximation would suggest so (3.12000000000000010658141036401502788066864013671875). In simpler terms, can we rely on the ...

Resolving Challenges with AngularJS Form Validation and Submission

I am currently working on a project using AngularJS where the user can activate their account, input their data, and submit JSON data upon completion. My Goal: When the user submits valid user data (within the JSON data), they should be redirected to &a ...

Can the V8 JavaScript engine made by Google be used on iOS devices?

Is V8 compatible with iOS? If not, what embeddable JavaScript engine would you suggest? UPDATE: We will only be using it for internal scripting purposes, rather than in combination with HTML rendering. ...

How can I effectively enable the close button on the NbAlertComponent to dismiss an alert?

I have been utilizing the nebular framework in my project and I am struggling to figure out how to make the close button of the NbAlertComponent actually close the alert. When I say close, I mean stop displaying the alert after clicking on the close button ...

Having trouble making radio buttons clickable with jQuery/JS?

Having a minor issue as a beginner, I am struggling to make buttons within a DIV clickable. The top line consists of 5 buttons that work perfectly. When clicked, a 2nd row appears as expected, but for some reason, I can't click on them. What could be ...