Removing single quotes and replacing them with spaces when passing data from JavaScript to MySQL

I'm currently focused on JavaScript using Hapi.js in my role at the company. My main task involves retrieving data from MongoDB and transferring it to a MySQL database.

The challenge arises when dealing with data that contains single quotes within the MongoDB collection. For instance, if I have a record like "O'Neill", inserting it into MySQL becomes tricky. While I came across the escape() function, it replaces the single quote with "%" followed by a hexadecimal number.

If feasible, I would prefer to retain the single quote; otherwise, replacing it with a space is acceptable.

Do you have any suggestions or solutions for this issue?

Thank you!

con.connect(function(err) {
    if (err) throw err;
    accounts.forEach((account) => {
        const sql = "INSERT INTO 2018_ACCOUNTS (ID, LOGIN, FIRST_NAME, LAST_NAME, DATE, EVENT, UNIK) VALUES ('" + account._id + "', '" + account.login 
+ "', '" + account.name + "', '" + account.name2 + "', '" + dateMySQL + "', " + account.evt_id + ", '" + account.unik + "')";
    con.query(sql, function (err, result) {
        if (err) throw err;
    });
});

This snippet of code illustrates the problem where individuals with single quotes in their names are not being added to the MySQL database.

Answer №1

Give this code a try

Try using the following SQL query:

const sqlQuery = "INSERT INTO 2018_ACCOUNTS (ID, LOGIN, FIRST_NAME, LAST_NAME, DATE, EVENT, UNIK) VALUES (?,?,?,?,?,?,?)";
    connection.query(sqlQuery,[account._id ,account.login ,account.name, account.name2, dateMySQL ,account.evt_id ,account.unik], function (error, 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

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...

Get canvas picture through JS Jquery

I've been attempting to save a canvas image to my desktop using this code: <script type="text/javascript"> var canvas; $(document).ready(function() { if ($('#designs-wrapper').length) { $('.design').eac ...

Guide to displaying numerous points on mapbox by utilizing a for each loop statement

I have a 2D array containing longitudes and latitudes that I need to map using MapBox. The example I found only demonstrates plotting two points, so I attempted to use a for-each loop to iterate through my 2D array and plot all the points. However, I enco ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

How to dynamically add an input textbox after a selection change in YUI JavaScript?

Is there a way to add an extra input textbox after an onchange event in a selectbox using the YUI library? I need to utilize YUI and the form is generated with PEAR Quickforms lib. This is what I have so far: $form->addElement('select', &ap ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

Is there a way to automatically increase a value by clicking on it?

Check out this code snippet I'm working with: let funds = document.createElement('funds') funds.style.color = 'green' funds.style.textAlign = 'center' funds.style.fontSize = '50px' funds.style.backgroundCol ...

Is it advisable to optimize your SEO by placing the JavaScript code at the bottom of your webpage?

Is this just an urban legend or is it actually true? I've heard that when web crawlers analyze a webpage, they have a time limit to capture all available code (like html) before moving on to the next page. If the JavaScript code is in the head sectio ...

I am unsure about how to properly implement the reduce function

I am struggling with implementing the reduce function in my code. I have data output from a map function that consists of two documents. For example, one document contains: key "_id":"AD" "values" { "numtweets" : 1, "hastags" : ...

Using Internet Explorer to watch full-screen HTML 5 videos

I am in the process of developing my own HTML 5 Browser Player. Everything seems to be working well, except for getting the full screen feature to function properly in IE 10. Chrome, Safari, and Firefox are all doing great with it. Unfortunately, my JavaS ...

Alter the status of a checkbox programmatically

There are two checkboxes available: <input type="checkbox" id="id3"></input> <input type="checkbox" id="id4"></input> The desired functionality is that when clicking on id3, id4 should also be checked. Initially, this works as e ...

Introducing additional choices to the list and automatically refreshing the list with the latest updates

I am currently honing my skills in Yii2 by working on a project using this framework. One of the challenges I am facing is adding new list options dynamically without having to navigate away from the current page. When I click the "Add new option" button ...

Can a client component in NextJs retrieve data from a server component?

Apologies for the way the question is phrased. I have a server component named auth.ts that retrieves user details after they log in. This server side component is located at //auth.ts export const validateRequest = cache( async (): Promise< { use ...

Implementing AJAX and mySQL in jQuery Sortable

Hello, I have successfully implemented a sortable list on the backend of my website to manage categories. The list updates the database using an Ajax call without needing to reload the page. However, I am facing an issue where the order number displayed in ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Using async/await with Axios to send data in Vue.js results in different data being sent compared to using Postman

I am encountering an issue while trying to create data using Vue.js. The backend seems unable to read the data properly and just sends "undefined" to the database. However, when I try to create data using Postman, the backend is able to read the data witho ...

Unable to halt operation when xmlhttprequest.responseText is equal to a particular value

Currently, I am incorporating XmlHttp with Java servlets in the following manner: function btnSave_onclick(){ var xmlHttp; var responseText; if (condition){ var para= "someParamsHere"; var url = "urlHere"; if (window.XMLHttpRequest) { ...

What is the best way to place a floating elastic div on top of an elastic background and ensure that the div stays in place?

Looking for some creative input here. Don't have a specific question in mind, but open to ideas. Just to clarify, I want both the floating div and the background to resize as the window size changes, while keeping the div in the same position on top ...

The cube mesh is failing to render inside the designated div

I created a Torus and Cube Mesh in my scene, but I want the cube to be positioned at the bottom right corner of the screen. Here's what I tried: <div style="position: absolute; bottom: 0px; right:0px; width: 100px; text-align: center; "> & ...