The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are

\x00, \n, \r, \, ', " and \x1a.

This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.

Answer from James Allardice on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.mysql-real-escape-string.php
PHP: mysql_real_escape_string - Manual
Escapes special characters in the ... library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a....
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ func_mysqli_real_escape_string.asp
PHP mysqli real_escape_string() Function
The real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in an SQL query, taking into account the current character set of the connection.
Discussions

php - what does mysql_real_escape_string() really do? - Stack Overflow
One thing that I hate about documentation at times (when you're a beginner) is how it doesn't really describe things in english. Would anyone mind translating this documentation for me? I'd like to... More on stackoverflow.com
๐ŸŒ stackoverflow.com
is mysql_real_escape_string enough?
You should read up on PDO, its perfectly crafted for handling issues such as injections with prepared/binded statements. PDO Intorduction PDO Prepared Statements More on reddit.com
๐ŸŒ r/PHP
45
21
April 17, 2011
php - mysql_escape_string VS mysql_real_escape_string - Stack Overflow
I know that mysql_escape_string is deprecated from 5.3 but what was the actual difference in mysql_real_escape_string. What I thought was that mysql_real_escape_string is the exact same as More on stackoverflow.com
๐ŸŒ stackoverflow.com
mysql - How to use mysql_real_escape_string function in PHP - Stack Overflow
So in this program I'm writing, I actually grab a SQL query from the user using a form. I then go on to run that query on my database. I know not to "trust" user input, so I want to do sanitizati... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Top answer
1 of 6
88

The function adds an escape character, the backslash, \, before certain potentially dangerous characters in a string passed in to the function. The characters escaped are

\x00, \n, \r, \, ', " and \x1a.

This can help prevent SQL injection attacks which are often performed by using the ' character to append malicious code to an SQL query.

2 of 6
61

Say you want to save the string I'm a "foobar" in the database.
Your query will look something like INSERT INTO foos (text) VALUES ("$text").
With the $text variable replaced, this will look like this:

INSERT INTO foos (text) VALUES ("I'm a "foobar"")

Now, where exactly does the string end? You may know, an SQL parser doesn't. Not only will this simply break this query, it can also be abused to inject SQL commands you didn't intend.

mysql_real_escape_string makes sure such ambiguities do not occur by escaping characters which have special meaning to an SQL parser:

mysql_real_escape_string($text)  =>  I\'m a \"foobar\"

This becomes:

INSERT INTO foos (text) VALUES ("I\'m a \"foobar\"")

This makes the statement unambiguous and safe. The \ signals that the following character is not to be taken by its special meaning as string terminator. There are a few such characters that mysql_real_escape_string takes care of.

Escaping is a pretty universal thing in programming languages BTW, all along the same lines. If you want to type the above sentence literally in PHP, you need to escape it as well for the same reasons:

$text = 'I\'m a "foobar"';
// or
$text = "I'm a \"foobar\"";
๐ŸŒ
Sqlinjection
sqlinjection.net โ€บ advanced โ€บ php โ€บ mysql-real-escape-string
mysql_real_escape_string SQL injection - Correct Usage and Attacks
PHP provides mysql_real_escape_string() to escape special characters in a string before sending a query to MySQL. This function was adopted by many to escape single quotes in strings and by the same occasion prevent SQL injection attacks.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ sql โ€บ sql-injection-that-gets-around-mysql-real-escape-string
SQL Injection that Gets Around mysql_real_escape_string() Function - GeeksforGeeks
July 23, 2025 - mysql_real_escape_string() is a PHP function designed to escape special characters in a string before inserting them in MySQL queries, ensuring safe MySQL queries are run in the database.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ php-mysqli_real_escape_string-function
PHP | mysqli_real_escape_string() Function - GeeksforGeeks
April 28, 2025 - The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may ...
๐ŸŒ
OnlinePHP
onlinephp.io โ€บ mysql-real-escape-string โ€บ manual
mysql_real_escape_string - OnlinePHP.io Example
Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query. If binary data is to be inserted, this function must be used. mysql_real_es...
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/php โ€บ is mysql_real_escape_string enough?
r/PHP on Reddit: is mysql_real_escape_string enough?
April 17, 2011 -

I'm still new to PHP and as part of my self education I'm hand-coding a CMS. So far all I've managed to make it do is dynamically pull page data. What content gets displayed depends on the value given in a $_GET variable. If one isn't present, it defaults to the homepage. That took a while to figure out...so many errors...

But anyway, I realized that since the GET ends up being part of my mysql query, I should probably secure it against SQL injection. My question is if running GET through mysql_real_escape_string() is enough to do that? Is there more I should/could be doing?

Or do I even need it in this specific case? This is how the $_GET is being used in my query-

$pull_page_data = mysql_query("SELECT * FROM pages WHERE page_id = '$page'");

Can havoc still be caused at the end of the query?

But back to the primary question, is doing this enough to secure my database from a basic sql injection?

$page = mysql_real_escape_string($_GET['page']);

Thanks, guys!

๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ web-development โ€บ threads โ€บ 290364 โ€บ mysql-real-escape-string-help
php - Mysql_real_escape_string HELP [SOLVED] | DaniWeb
It should be if ($num2 > 0) so you are testing the result of the second query, not the first. Also, your early warnings came from mixing mysql_* with mysqli_*. Stick to mysqli and only call real_escape_string on an active connection (and after setting the connection charset when needed).
๐ŸŒ
Pegasusinfocorp
pegasusinfocorp.com โ€บ web_development_knowledgebase โ€บ phpmanual โ€บ function.mysql-real-escape-string.html
mysql_real_escape_string Web Development Pegasus InfoCorp
Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used ยท mysql_real_escape_string() calls MySQL's library function ...
๐ŸŒ
w3resource
w3resource.com โ€บ php โ€บ function-reference โ€บ mysqli_real_escape_string.php
PHP mysqli_real_escape_string() function / mysqli::real_escape_string - w3resource
August 19, 2022 - <?php $link = mysqli_connect("localhost", "user1", "datasoft123", "hr"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City"); $city = "Kalkata"; /* this query will fail, cause we didn't escape $city */ if (!mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) { printf("Error: %s\n", mysqli_sqlstate($link)); } $city = mysqli_real_escape_string($link, $city); /* this query with escaped $city will work */ if (mysqli_query($link, "INSERT into myCity (Name) VALUES ('$city')")) { printf("%d Row inserted.\n", mysqli_affected_rows($link)); } mysqli_close($link); ?>
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ php โ€บ mysqli_real_escape_string.htm
PHP mysqli_real_escape_string() Function
The mysqli_real_escape_string() function is used to escape characters in a string, making it legal to use in an SQL statement. The mysqli_real_escape_string() returns a legal string which can be used with SQL queries.
Top answer
1 of 1
4

No. You've missed escaping the contents of $each before that's included in the SQL text, here:

    $query .= "keywords LIKE'%$each%'";

Our preference would be to avoid using the deprecated mysql_ functions, and use PDO or mysqli interfaces. And we'd prefer to use prepared statements with bind placeholders. They really aren't that hard.

If I was going to "escape" potentially unsafe values included in the SQL text, I'd first break up that assignment, to look like this.

  $query .= "keywords LIKE '%" . $each . "%'";

Now, we can "wrap" that variable reference in a function call, something like this:

  $query .= "keywords LIKE '%" . mysql_real_escape_string($each) . "%'";

You'd need to repeat that pattern wherever you are including potentially unsafe values as part of the SQL text.

And it's not necessary to wrap $username and $password in the connection arguments. That's not a SQL statement. What needs to be "escaped" are values that are included in the text of a SQL statement.


Again, our preference would be to use either PDO or mysqli, and use a prepared statement with bind placeholders. For example:

  $query .= " keywords LIKE CONCAT('%', ? , '%')";

Also, the values you are including in the HTML could include some potentially dangerous content. It's a good practice to run that through proper escaping. In some cases http://php.net/manual/en/function.htmlspecialchars.php is sufficient.


As an aside, when dynamically appending to a string containing SQL text, my preference is to include the required separator space at the beginning of what I'm adding, rather than having to remember to include an extra space at the end of the string I'm appending to. That's just a personal preference.

Top answer
1 of 3
2

You should never use anything "to reduce the likelihood of SQL injections" in the first place. It just doesn't work this way. You are not adding some code just in case, sort of a rabbit foot. SQL injections simply must be prevented, using certain tools. It is so easy to achieve that it just should go without saying. Just never add any variable to your SQL queries - that's all. Here is how. It doesn't only prevent injections but also relieves you from that escaping mess.

That said, no extra slashes should appear in the output unless there is an error in your code. Escaping is used for the query only, it is not stored in the database. So instead of removing extra slashes you must not add them in the first place.

2 of 3
2

No, it's not safe, because what you are doing is wrong. In your code you are echoing a variable that has only been sanitized using mysqli_real_escape_string (https://www.php.net/manual/en/function.mysql-real-escape-string.php). All that function does is prepend backslashes to some characters, like the single quote, the new line character, etc. This function was only meant to sanitize a string before using it in an SQL statement. By the way, today it is considered bad practice to use such a function, and the recommended way to make queries to the database is to use prepared statements. It's a totally different way to make queries, and you will need to use another set of PHP functions and objects.

To echo something on an HTML web page you can't use mysqli_real_escape_string for sanitization, because the set of dangerous characters is different. In HTML, you need to escape the < and > characters, for example. Other characters might have to be escaped depending on where you are echoing them, for example the single or double quote. Also, the escaping method is different from the one used for SQL: a single quote in HTML won't be prepended with a backslash when escaped, but will need to be replaced with an HTML entity, becoming &apos;. A PHP function you might use for this is htmlspecialchars (https://www.php.net/manual/en/function.htmlspecialchars.php).

Top answer
1 of 2
6

The main shortcoming of mysql_real_escape_string, or of the mysql_ extension in general, is that it is harder to apply correctly than other, more modern APIs, especially prepared statements. mysql_real_escape_string is supposed to be used in exactly one case: escaping text content that is used as a value in an SQL statement between quotes. E.g.:

$value = mysql_real_escape_string($value, $link);
$sql = "... `foo` = '$value' ...";
                     ^^^^^^

mysql_real_escape_string makes sure that the $value in the above context does not mess up the SQL syntax. It does not work as you may think here:

$sql = "... `foo` = $value ...";

or here:

$sql = "... `$value` ...";

or here:

$sql = mysql_real_escape_string("... `foo` = '$value' ...");

If applied to values which are used in any context other than a quoted string in an SQL statement, it is misapplied and may or may not mess up the resulting syntax and/or allow somebody to submit values which may enable SQL injection attacks. The use case of mysql_real_escape_string is very narrow, but is seldom correctly understood.

Another way to get yourself into hot water using mysql_real_escape_string is when you set the database connection encoding using the wrong method. You should do this:

mysql_set_charset('utf8', $link);

You can also do this though:

mysql_query("SET NAMES 'utf8'", $link);

The problem is that the latter bypasses the mysql_ API, which still thinks you're talking to the database using latin1 (or something else). When using mysql_real_escape_string now, it will assume the wrong character encoding and escape strings differently than the database will interpret them later. By running the SET NAMES query, you have created a rift between how the mysql_ client API is treating strings and how the database will interpret these strings. This can be used for injection attacks in certain multibyte string situations.

There are no fundamental injection vulnerabilities in mysql_real_escape_string that I am aware of if it is applied correctly. Again though, the main problem is that it is terrifyingly easy to apply it incorrectly, which opens up vulnerabilities.

2 of 2
0

Ok, so apart from mysql_* being deprecated, I understand your wanting to know about any possible workaround that might exist. perhaps this blog post and the slides might reveal some of them.
But as this older question here shows, casting and quoting isn't full proof. There's just So many things that can wrong, and Murphy's law, twined with that ever valid mantra "Never trust the network", will go horribly wrong.

Perhaps this article, but most importantly, the follow-up to that article can reveal even more security issues. To be honest, I know mysql_real_escape_string isn't fullproof, even in combination with type casting and string formats:

printf('WHERE id = \'%d\'',(int)mysql_real_escape_string($_REQUEST['id']));

doesn't cover every possible attack.
I'm no expert on this matter, but what I can tell you is sanitizing every input, will, if anything, give you a FALSE sense of security. Most of the time, you'll know (initially) what and why and how you protect against the attacks, but your colleagues might not. They might forget something, and your entire system is compromized.

In summary: Yes, you might be able to prevent any form of malicious input from getting to your DB, but every additional action it requires is an added risk. In that scenario, the greatest liability (as always) is the developer that hasn't had is fourth cup of coffee on a monday morning. No code, no matter how defensive and well thought out, can protect itself from the monster that is a tired developer with a bad temper, going cold turkey on caffeine and nicotine.