EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial mysql_real_escape_string
Secondary Sidebar
MySQL Tutorial
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Partitioning
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Interview Questions
    • MySQL Interview Questions

Related Courses

MS SQL Certification Courses

Oracle Certification Courses

PL/SQL Certification Courses

mysql_real_escape_string

By Priya PedamkarPriya Pedamkar

mysql_real_escape_string

Introduction to mysql_real_escape_string

mysql_real_escape_string() is used to escape special characters like ‘\’,’\n’ etc in a query string before sending the query to mysql server. The given unescaped_string is encoded and returns an escaped sql string as an output. mysql_real_escape_string() function returns the length of the encoded or escaped sqlstring. This mysql_real_escape_string() function is used to Escapes special characters like \,\n in a string that can further used in the sql statement.

Syntax and Parameters

Below is the syntax of the mysql_real_escape_string() function:

String mysql_real_escape_string(string unescaped_string,resource link_identifier= =NULL);

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

This function contains two arguments, first is unescaped_string and the second is link identifier.

mysql_real_escape_string calls the function, which adds a backslashes before the following special characters: \x00, \n, \r, \, ‘, ” and \x1a. This function must always be written with an exception to through an exception when any abnormal behavior happens to the data and to save the data before sending a query to mysql.

Parameters

unescaped_string: The given string needs to be escaped or encoded.

link_identifier: It is used to specify the link for establishing a connection. If the link identifier is not stated, the last link opened by mysql_connect is supposed. If no link is established, it will create one link with mysql_connect function with no arguments passed. At last, after doing all this, then also if we are failing in establishing the connection with the link it will display an e-warning error message in the console.

Return Values: it will either returns an escaped string as an output if everything will be right otherwise it will display an error message or returns FALSE flag in the output console.

Errors/Exceptions: If we execute the mysql_real_escape_string function without establishing the connection of function with the mysql server then it will throw an E_warning message. mysql_real_escape_string() function will only get executed when the full connection is established with the mysql server. Executing this function without a mysql connection present will also through E_warning as an error message. Only execute this function with a valid mysql connection present. It is very important that the function is able to escape the string otherwise the query gets susceptible to sqlinjection (sqli) attacks.

Sql injection: It is a mechanism that allows an attacker or hacker to view data that cannot be easily retrieved. This includes data of the other users or the data that only the application access it itself.

The special characters that cannot be escaped by mysql_real_escape_string function are % (percentage)and _(underscore).If these two characters are combined with a clause like grant, revoke, and like these are called wildcards in MySQL. _(underscore matches a single character in as string)

%: matches any number of characters or zero numbers of characters in string.

It adds a backslash before every special character in the string given. List of special characters that mysql_real_escape_string can encode are shown below:

0x00 (null)
Newline (\n)
Carriage return (\r)
Double quotes (")
Backslash (\)
0x1A (Ctrl+Z)

We should be very careful while using mysql_real_escape_string() function to encode numeric parameters since they are usually written in the query without quotes. Below sample code shows if the mysql_real_escape _string is not implemented properly it could lead to sql injection.

Examples of mysql_real_escape_string

Following are the examples are given below:

Example #1

Suppose,the numeric user input is

500 OR 1=1

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,171 ratings)

Sanitizing input

$prod_id = mysql_real_escape_string($_GET['id']);

Below is the generated query:

select prod_name from product where id=500 OR 1=1

The above-mentioned query will lead to sql injection since the id parameter is not enclosed within quotes.

Note: In order to avoid SQL injection(sqli), the parameter passed in the function must be enclosed between quotes.

Correction in the query to avoid sql injection is shown below in the query.

select prod_name from products where id=500 OR 1=1'

Since the id parameter in the above query is within quotes it will not lead to sql injection.

Like Operator

The function does not escape SQL wildcards for LIKE operator. Since these characters cannot be escaped, they are measured as classic wildcards by the LIKE operator: To prevent this from error we will use a backslash before the wildcard LIKE operator.

Example #2

User_input
Xyz’spq_

Escape all characters:

$value=mysql_real_esape_string($_GET[‘p’]);
$value=str_replace(“%”,”%”,$val);
$value=str_replace(“_”,”_”,$val);

Query

select * from employee where name LIKE ‘%Xyz\’s pq\_%’;

Disadvantages of the Function

Without any doubt, the mysql_real_escape_string function is the best way to avoid sql injections. But it has some demerits also like if we call the function so many times, the database server will get down slow. However, if we call the function twice on the same data by mistake we will have incorrect information or data in our database. Because of all these mentioned reasons, we can implement alternative solutions for example parameterized statements method or stored procedure.

Unsigned long mysql_real_escape_string(mysql * mysql,char * to,const char * from,unsigned long);

  • mysql: a mysqllink, that was connectedpreviously by mysql_init() or mysql_real_connect().
  • to: the encoded string. In the worst scenario, every character of the string needs to be escaped. Moreover, a 0 character will be appended.
  • from: a given string that needs to be encoded by the function.
  • long: the length of the given string.

Example #3

//establish connection with the mysql server
$link=mysql_connect(‘mysql_host’,’mysql_user’,’mysql_password’);
//sql query
$query=print(“select * from employee where user_name=’%s’ and pass-word=’’%s”,mysql_real_escape_string($user_name),mysql_real_escape_string($pass_word));
select * from employee where user_name=”%ta” and pass_word=”_123”

This query will login to the system with employee username ending with “ta” and starting with any number of characters and having a password with any single alphabet followed by 123.

Conclusions

In this article, we have learned how to use the mysql_real_escape_string() function. We have also learned to use the function to avoid sql injection. We have also learned about the specials characters that can be escaped by this function. The function is explained with various examples for a better understanding of the user.

Recommended Articles

This is a guide to mysql_real_escape_string. Here we also discuss syntax and parameter along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. MySQL REVOKE
  2. MySQL DML
  3. MySQL Window Functions
  4. MySQL Foreign Key 
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (14 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
2 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more