• Register

Mysql_real_escape_string () function is used to handle string in PHP MySQL. When this function is used it removes all special characters from the string which will be later used in the SQL query.  This function returns a value and it was supported from PHP version 5+.

Purpose of mysql_real_escape_string in PHP

Mysql_real_escape_string is used to provide MySQL a valid and legal query. This function eliminates all special characters from the query string.

Syntax and Parameters

Mysql_real_escape_string () has syntax depending on the programming technique you are following. It can be used in procedural and object-oriented programming techniques.

Procedural style:

mysqli_real_escape_string(connection, escapestring)

In procedural style, it takes two parameters one is the connection which checks if the connection to the server is enabled. And the other parameter is the escape string which is the real string to be filtered from special characters. 


$con = mysqli_connect("localhost","user","assword","database");

if (mysqli_connect_errno()) {
  echo "No database connection " ;

// Escape special characters
$first_name = mysqli_real_escape_string($con, $_POST['name']);
$last_name = mysqli_real_escape_string($con, $_POST['last_name']);

$sql="INSERT INTO visitor(first_name, last_name) VALUES ('$first_name', '$last_name')";

if (!mysqli_query($con, $sql)) {
  printf("%d Rrecord created.\n", mysqli_affected_rows($con));


OOP style: 

$mysqli -> real_escape_string(escapestring)

In an object-oriented style, we provide a single parameter which is the escapestring, and the connection parameter is provided by the object.


$mysqli = new mysqli("server","username","password","database");

if ($mysqli -> connect_errno) {
  echo "database connection is not created: ";

// check and escape characters if any 
$name = $mysqli -> real_escape_string($_POST['name']);
$last_name = $mysqli -> real_escape_string($_POST['last_name']);

$sql="INSERT INTO customer (name, last_name) VALUES ('$firstname', '$lastname')";

if (!$mysqli -> query($sql)) {
  printf("%d Record inserted.\n", $mysqli->affected_rows);
  // if the record inserted it will show a message

$mysqli -> close();

Mysql_real_escape_string () and supported version of php

Mysql_real_escape_string was used in PHP version 5.4 and it was depreciated in PHP version 5.0. You cannot use this in the latest or updated PHP versions.it is not supported in PHP version 7 and will through an error warning. Alternate of mysql_real_escape_string is mysqli_real_escape_string.

7,490 points
10 5 2