• Register
4,670 points
9 5 1

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. 

Example:

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

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

// 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));
}

mysqli_close($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.

Example:

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

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

// 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.

4,670 points
9 5 1