What are some examples of MySQL node insertion queries with a pair of values?

I need help with my current JavaScript code snippet.

var connection = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: 'root',
   database: 'codify',
   port:     '8889'     
})


connection.connect();
 //var querydata = +"'"+data.RegUsername + "','"+data.RegPassword+"'" 
  connection.query("INSERT INTO Codify (UsernameDB , PasswordDB) VALUES ?", data.RegUsername,+","+ data.Regpassword , function(err,rows,fields){
   if (err) throw err;
    })
  });*/

This specific SQL query is causing an error for me, can anyone please point out what I am doing incorrectly?

Answer ā„–1

The mistake you're making is attempting to combine your two values into a single string and then substituting that string into a single ?. When using a single ?, you should pass in an object where the object's properties match the database field names.

You could approach it like this:

let payload = {
    UsernameDB: data.RegUsername,
    PasswordDB: data.Regpassword
};

connection.query("INSERT INTO Codify SET ?", payload, function(err, rows) {

});

Another way is by using an array instead of an object:

let sql = "INSERT INTO Codify (UsernameDB, PasswordDB) VALUES (?, ?)";
connection.query(sql, [ data.RegUsername, data.Regpassword ], function(err, rows) {

});

Alternatively, you can do it like this:

let sql = "INSERT INTO Codify SET UsernameDB = ?, PasswordDB = ?";
connection.query(sql, [ data.RegUsername, data.Regpassword ],  function(err, rows) {

});

However, I personally find using a single ? along with an object to be more legible.

Answer ā„–2

When writing queries, it's important to use placeholders like the ? character to escape your data and prevent SQL injection attacks. Instead of concatenating strings in your query, insert each value using placeholders. For example:

("INSERT INTO UserData (Username , Password) VALUES (?,?)", [userData.username, userData.password])

For more information on how to properly escape query values in Node.js MySQL driver, check out the documentation here.

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 React's debounce feature in conjunction with updating state using

Introduction Let's discuss the popular debounce function provided by lodash. Imagine a scenario where a user rapidly enters values like 1, 12, 123, 1234. The debounce function ensures that only one alert, with the final value 1234, is triggered afte ...

Is there a specific index range in javascript or nodejs for accessing array items?

I recently came across this Ruby code snippet: module Plutus TAX_RATES = { (0..18_200) => { base_tax_amount: 0, tax_rate: 0 }, (18_201..37_000) => { base_tax_amount: 0, tax_rate: 0.19 }, (37_001..80_0 ...

Using jQuery to Retrieve an Element's Class Through an AJAX Call

For my website, I am using ajax to load pages by replacing the content in the main tag. The issue arises when working with Wordpress, as each page has its own set of body classes for styling purposes. My goal is to replace the old page's body classes ...

Tips on organizing orders by various cities with Laravel, MySQL, and JSON

I am currently working on generating a report with order-related information from a Laravel project. However, I am facing challenges in determining the specific data structure required for this task. Here is what I need: // Date Ranges $fromDate = $this- ...

Adjusting the color of specific sections within a text box

Can I change the color of a specific section of a text input box? I'm working on a comment widget that needs everything between the @ and : symbols to be in a different color: <input type="text" placeholder="Want To Say Something?" value="@user55 ...

Verify whether the value of the Object matches the value of the string

Currently, I have a situation in ES6 where I am utilizing Vue.js for the current module. The task at hand is to verify if a specific string value exists within an array object. let obj1 = [{name: "abc ced", id: 1}, {name: "holla' name", i ...

Unable to retrieve a return value from an asynchronous waterfall function within a node module

A custom node module that utilizes async waterfall is working properly when run independently, but the AJAX callback does not receive the return value. //Node module var boilerplateFn = function(params){ async.waterfall([ function(callback){ ...

Emberjs Troubleshooting: Issue with Sending Many-To-Many JSON Parameters

My current versions are ember-cli 1.13.8 and ember-data 1.13.11, using ActiveModelAdapter. I am working with two objects: posts and users. On an individual post page, I have implemented an action that allows users to watch/follow the post. //post model j ...

A guide to specifying the Key-Callback pair types in Typescript

Here is an object containing Key-Callback pairs: const entitiesUIEvents = { newEntityButtonClick: () => { history.push("/entity-management/entities/new"); }, openEditEntityDialog: (id) => { history.push(`/entity-mana ...

Updating or editing data in a database using AngularJS: A step-by-step guide

Recently, while working on a web application, I included the following update code but it seems to not be functioning as intended. To provide an overview: Upon clicking a Button named update A FORM should appear displaying the details of the product tha ...

Having trouble parsing data in a jQuery REST call

After creating a web service using Slim Framework 3 in PHP, all data is returned using the following instruction: return $response->withJson($liste); I then created an HTML client using the "jquery.rest" plugin to view the JSON results. However, I am ...

Utilize AngularJS to load pages through a single state

Is there a way to develop a method that can dynamically load the controller and template for each page as needed, upon changing routes? I am looking to enhance the state url option by including 2 parameters, with the second one being optional. This would a ...

Challenge with AngularJS ng-select and ng-switch-when functionality

Struggling with implementing a selection menu on my angular charts, I encountered some challenges. The selection app template I used only displays the selection menu and graph axis on the page. Checking the console log for errors, I noticed one src URL wa ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

The web browser's engine is blocking the connection to the secure websocket server

Summary of Issue An error message stating "Websocket connection failed." appears in the browser console (Chrome or Brave) when trying to run this code: const ws = new WebSocket("wss://abcd.ngrok-free.app/") (Please note that the URL mentioned is not real ...

Logging into a MySQL database on an Android device

Hey there everyone, I'm currently working on implementing a basic login system in Android that connects to an online MySQL database. Here is the approach I've taken so far: MainActivity: protected String doInBackground(String... args) { s ...

Bring in resources without specifying

Is there a way to directly import an image into a JSX tag in React without having to declare it at the top of the file using import img from './this/is/file.png'? I attempted to do so with <img src={import './this/is/file.png'} alt= ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Unable to render data in Chart JS using PHP JSON

Hello, Iā€™m currently working on creating a dynamic line chart using Chartjs. The data is being pulled from an SQL database using PHP in JSON format. Although the data is successfully retrieved, the chart appears blank. Any assistance would be greatly app ...

Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat ...