Can I use the LIKE operator in a SQL query without worrying about SQL Injection vulnerabilities?

When dealing with POST data (json) in my express app, I have an endpoint that allows me to query a MySQL database safely. However, I am concerned about potential vulnerabilities when escaping and altering strings. Is there a risk of exploitation?

The goal is to modify the incoming string by inserting a '%' before the closing single quote in the LIKE clause.

var searchTerm = mysql.escape(req.body.firstName)
var newStr = "'" + searchTerm.substring(1, searchTerm.length - 1) + "%'"

// Example:  'alex' => 'alex%'

This method works fine, but I am curious if there is a more secure or recommended way to achieve this task.

Current query being used:

SELECT * FROM tbl WHERE col LIKE " + newStr + " ORDER BY key

For those seeking reference:

UPDATE/ANSWER

In response to EternalHour's suggestion, a more appropriate syntax would be:

var newStr = req.body.firstName + "%"
var sql = "SELECT cols FROM tbl WHERE col LIKE ? ORDER BY key"
sql = mysql.format(sql, newStr)

Answer №1

In accordance with Christian's suggestion (but in a different programming language), it is advised to utilize prepared statements for enhanced security. It appears that you will need to modify your string to eliminate the single quotes, as prepared statements usually handle escaping automatically. This particular library seems to follow the same protocol.

Although unfamiliar with this specific library, it would likely look something like this:

var query = "SELECT * FROM tbl WHERE col LIKE ? ORDER BY key";
var newStr = searchTerm.substring(1, searchTerm.length - 1) + "%";
sql = mysql.format(query, newStr);

Additionally, it is recommended not to use * in SQL select queries.

Answer №2

Test out the fresh newStr directly by using the code snippet below (avoid adding % explicitly) :

SELECT * FROM tbl WHERE col LIKE '" + newStr + "%' ORDER BY key

Answer №3

It is recommended to use a Prepared Statement for this task:

In C#:

//Creating a new SQL Command with the parameter @newStr
var command = new SqlCommand( "SELECT * FROM tbl WHERE col LIKE '@newStr' ORDER BY key", db);

//Setting the parameter @newStr to 40 characters
command.Parameters.Add("@newStr", SqlDbType.VarChar, 40);

//Preparing the statement after defining all parameters
command.Prepare();

//Setting Parameter @newStr to "newStrValue"
command.Parameters["@newStr"] = "newStrValue";

//Executing the Command
command.Execute();

For Node.js, there is a Package that supports prepared Statements:

https://www.npmjs.com/package/mysql2

By using Prepared Statements, you can prevent SQL Injection attacks as the Database recognizes user input and not as a direct SQL Command.

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

Adjust background dimensions using jQuery

Having trouble adjusting background-size using jQuery? It seems to work with a single parameter, but not with two. I'm trying to set both width and height via jQuery variables. Here's an example of my JavaScript code: var w = 100; var h = 100; ...

JavaScript closing of a window

I've been dealing with this issue for the past few hours. Currently, I am utilizing the iframe version of LightFace modal windows: http://davidwalsh.name/facebook-lightbox The problem I'm encountering is the inability to close the modal from w ...

What is the best way to retrieve the maximum row number within each group or partition in SQL Server?

In my SQL Server 2005 database, I am dealing with a payments table that contains payment ids, user ids, and timestamps. My goal is to determine the most recent payment for each user as well as whether it is their first payment or not. Although finding the ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

In a Ruby on Rails application, utilize jQuery to display an alert when a user does not accept the

Within my Ruby on Rails application, I have a form structured as follows: = simple_form_for @reservation do |f| = f.input :terms, as: :boolean = f.submit t('reservation.next'), class: "btn btn-default pull-right" Inside the model, there is ...

JSP page displaying a table with a text input field named "code" enclosed within <TD> tags

Recently, I designed a JSP page that features a table with two columns: Code and Description. The table data is an input type of "text" with the name attribute set to "code". The main functionality I need to implement is the automatic generation of the d ...

Is there a way to achieve this without relying on Ext.getCmp in this particular code snippet?

I am currently using the following code to trigger a button click event once the window show event is called. It works perfectly fine, but I want to achieve the same functionality without using Ext.getCmp. Here is the line of code: Ext.getCmp('recen ...

Experiencing difficulties with setting up SearchApp

Issue: I am encountering a problem with my cloudant account after attempting to install the SearchApp from this link. The installation process was successful, but when I try to use the search functionality on the site, nothing happens. Query The website ...

send data to a Node.js application using the POST method

I am currently running the following node application (relevant part provided): app.post("/create_customer_portal_session",async (req, res) => { const {customerId} = req.body; var session = await stripe.billingPortal.sessions.create({ ...

AngularJS Toggle Directive tutorial: Building a toggle directive in Angular

I'm attempting to achieve a similar effect as demonstrated in this Stack Overflow post, but within the context of AngularJS. The goal is to trigger a 180-degree rotation animation on a button when it's clicked – counterclockwise if active and c ...

Formatting dates in PHP with a mySQL query

I am facing an issue with formatting the dates retrieved from my mySQL database. Below is the code I am using: <?php function get_gold_time() { $goldquery = mysql_query("SELECT * FROM metal_price WHERE metal= 'GOLD' LIMIT 0, 96"); ...

My SQL query has been optimized to be 40% more efficient, yet it now runs 60 times slower

I recently encountered a situation where I had SQL code generated by JPA that was 1250 lines long in the worst-case scenario. The query itself consisted of 20 sub-queries nested within the WHERE statement, yet surprisingly it executed in just 0.015 second ...

The showdown between AngularJS Directive Restrict A and E

In our small team, we are currently working on a project in AngularJS and striving to uphold basic standards and best practices. Since we are still relatively new to Angular, we have some questions regarding Directives, specifically the `restrict` options. ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...

Utilizing Athena to efficiently query map-type columns with dynamically changing key names

Currently, I am utilizing Athena Presto query to locate a value within a map type column. My goal is to identify a key/value pair with varying key names. Specifically, the keys will follow this format: abc_1, abc_2, ..., abc_100, always starting with a pre ...

Sending form data to the server using JavaScript: A step-by-step guide

Currently, I am dealing with the configuration of two servers. One server is running on React at address http://localhost:3000/contact, while the other is powered by Express at address http://localhost:5000/. My goal is to transmit form data as an object v ...

Counter cannot be accessed once it has been updated

When I click a button, an interval should start. The issue is that I'm unable to access the value of counter. The goal is for the interval to stop when the counter reaches 5. Here's an example: let interval = null; const stateReducer = (state, ...

Difficulty commencing a background operation in a node.js application

I have a setup using node.js/express and React for the client side code. This setup allows users to query any number of players by making fetch requests to my express server, which then sends requests to Riot Games public API. The issue I'm encounteri ...

Utilizing JavaScript to target a specific div element and modify the href attribute

I am currently working on adjusting the links within my page using JavaScript. While I am able to select the div and the a element, I am encountering difficulties in changing the href attribute. Shopify utilizes a for loop to generate these objects, and i ...

What do you want to know about Angular JS $http request?

My goal is to send a request using $http with angular js in order to retrieve a json object from google maps. $http.get('http://maps.googleapis.com/maps/api/geocode/json?address=' + data[ 'street' ] + ',' + data[ 'city&a ...