Is mysql(i)_real_escape_string a reliable method for ensuring data safety?

function CustomQuery()
{
    $arguments = func_get_args ();

    if (sizeof ($arguments) > 0)
    {
         $query_string = $arguments[0];

         for ($index = 1; $index < sizeof ($arguments); $index++)
                $query_string = preg_replace ("/\?/", "'" . mysql_real_escape_string ($args[$index]) . "'", $query_string, 1);
    }
    else
    {
          return FALSE;
    }

I have created a custom function to handle queries in my application. An example usage would be:

$this->CustomQuery('SELECT * FROM USERS WHERE Username = ? AND Points < ?', $username, $points);

This function currently uses legacy mysql functions, but switching to mysqli is simple by replacing occurrences of mysql with mysqli throughout the codebase.

Is the current method of using mysql_real_escape_string on each parameter safe enough against SQL Injection attacks? While it has worked without issues so far, should I consider switching to mysqli_real_escape_string for enhanced security?

Although I am aware of prepared statements in mysqli, personally I find using bindParam for every variable somewhat excessive.

What are your thoughts on this approach?

Answer №1

Implementing bound parameters is essential and should be a standard practice. It significantly enhances the security of escaping and preparing your data.

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'GBR';
$language = 'English';
$official = "T";
$percent = 100.0;

/* execute prepared statement */
mysqli_stmt_execute($stmt);

Is this approach truly excessive?

Reference Guide

Answer №2

Had a fantastic day today - successfully implemented a new database abstraction layer for the second time in a row.

Considering whether to use mysqli_real_escape_string for data sanitization?

Nope.
Remember, this function does not handle sanitization.

However, it is essential to utilize this function for formatting SQL string literals, ensuring your queries are executed correctly with no vulnerabilities. Always use this function for string formatting without any conditions.
Your queries are now secure and reliable, especially when substituting actual data with a ? mark (and remember to set SQL encoding using mysqli_set_charset() function).

If someone questions your method as flawed, ask them for a detailed snippet of code showcasing the alleged vulnerability.

On another note, there are some key points I'd like to highlight:

  1. Keep in mind that dynamic SQL query parts may involve more than just strings. Certain queries, such as those involving numbers or identifiers, require specific formatting which your function might not cater to.
    Consider using type-hinted placeholders to specify the appropriate format for different data types.

  2. Executing a query is just one aspect; retrieving results effectively is equally important. Streamline the process by obtaining results efficiently without unnecessary code complexity.
  3. Include a mechanism for inserting literal ? marks into queries without the need for parsing.

Feel free to explore my class, which follows a similar approach to yours but incorporates enhancements as discussed above. It may offer valuable insights or inspire you to incorporate a few improvements.

Answer №3

When opting for mysqli over mysql, it is recommended to utilize mysqli_real_escape_string for better security measures. Keep in mind that the order of parameters has been altered, with % and _ still not being escaped.

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

The error message "Type Error: val.toString is not a function - mysql npm" indicates

I'm encountering an issue with the 'mysql' package in NPM on a nodeJS backend and I'm puzzled by this error message: TypeError: val.toString is not a function at Object.escape (/Applications/MAMP/htdocs/nodeJS_livredor/node_modules/sql ...

What is the best way to verify a value is present in a MySQL column?

How can I go about selecting all rows from a database where the display column is 'Y' and the announcement column is not null? What method can I use to verify that a column has a value? $qry = "select * from school where dis ...

What are the steps for applying validation successfully?

Hello, I have a table containing various fields and I am looking to implement validation on these fields. The fields in question are as follows: user_mobile admin_mobile user_email admin_email All of these fields are stored in the same database. I would ...

How can we modify the position of a header from fixed to relative when the mobile drop-down menu is opened?

I am experiencing an issue with my responsive design. When viewed on a device that is less than 600px wide, the drop-down multi-level navigation overflows downward and does not scroll because the header has a fixed position. As a result, the tabs in the me ...

How should a function be called within a string while adhering to proper syntax?

Why do I keep encountering an error stating that the function name must be in a string? Or in some cases, it just runs without printing anything. What could I be overlooking? <?php $funName = "{'$oneRun()'}"; echo "Hello! You are currently e ...

Ensure to verify the user's login status before allowing them to add an item

I'm currently in the process of implementing a "favorite" feature on my website. Users have the ability to browse the entire website without having to log in, but they will need to login if they want to mark any favorites from search results. I&apos ...

Exploring the functionality of MySQL's LIKE operator on fields stored as JSON-encoded data

I've been struggling to retrieve a table row using the following query: SELECT * FROM `table` WHERE `field` LIKE "%\u0435\u0442\u043e\u0442%" The actual content of the field is: Field ------ ...

Error message "Authorization issue occurred while trying to call a function in the PHP webservice."

I am facing an issue with calling a web service. It successfully connects and returns its methods, however, when I call one of the functions, it throws an unauthorized error. Here is my code try { $service = new SoapClient("http://www.go-to-orbit.com/oo ...

Deactivating the PHP URL does not have any effect on my XAMPP localhost, but it does work on the server

After using the code provided to eliminate php from URLs, I encountered an issue where it works perfectly on my online server but fails to work on XAMPP local host. RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRul ...

PHP - Monitoring for File Existence

I'm trying to execute an exe file that generates txt files and then check if those txt files have been created. When I use xampp, I've tried dragging a test.txt file into the php scripts directory, but it doesn't work correctly. Also, if I ...

Step-by-step guide to restarting an MQTT subscriber using Node.js

Working on a Node Js and MQTT Project In this project, a device initially subscribes to a topic or list of topics and starts receiving messages published for those specific topic(s). An admin from the dashboard then assigns that device another new topic. ...

Sharing variables between controllers in LaravelPassing data between controllers in Laravel

Recently, I started learning Laravel and came across a scenario where I have two controllers: CartController with the function finalizeCart and PaymentController with the function postPayment. Now, I am trying to figure out how to transfer the variable " ...

Creating Custom Queries with Eloquent ORM: A Beginner's Guide

I'm in the process of developing a sleek API and utilizing eloquent ORM. However, I find myself needing to write my own queries on occasion, especially for more intricate database requests. After conducting some research, I attempted the following ap ...

PHP malware files are being generated without manual intervention

We have an AWS ec2 instance running CentOs that hosts 4 sites - one static HTML and PHP site, two Joomla (v3.4.5) sites, and one Opencart (v2.0.1.1) site. Recently, we discovered some unfamiliar files on our server which appear to be malware. After runnin ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Is there a way for me to send the items in my shopping cart via email to the website administrator for review

Due to the nature of our products, we are unable to have a traditional shopping cart checkout. Instead, we require the checkout button to email the entire cart back to the web moderator for approval. Currently, the system retrieves products from the data ...

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

File appears to be empty after passing through ajax request

I have encountered an issue with my ajax submit function. When I submit the function, worklogdetailsidschedule and shift_schedule are successfully inserted into the database. However, the filename_schedule, which is a file, appears empty in the database. ...

Extract information from page 1 to page 2 by utilizing ajax

Greetings, I am currently facing an issue with parsing data using the href get method to retrieve PHP by ajax on another page. Is this achievable? By the way, my framework of choice is CODEIGNITER. This is my HTML href code snippet: <a href="'.b ...