Current Location: Home> Function Categories> real_escape_string

real_escape_string

Escape special characters in a string for use in SQL statements.
Name:real_escape_string
Category:Uncategorized
Programming Language:php
One-line Description:Escape special characters in a string for use in SQL statements.

Definition and usage

real_escape_string() / mysqli_real_escape_string() function escapes special characters in a string for use in SQL queries while taking into account the current character set of the concatenation.

This function is used to create a legal SQL string that can be used in SQL statements. Suppose we have the following code:

 <?php

$lastname = "D'Ore" ;

$sql = "INSERT INTO Persons (LastName) VALUES (' $lastname ')" ;

// This query will fail because we did not escape $lastname
if ( ! $mysqli -> query ( $sql ) ) {
  printf ( "%d Row inserted.\n" , $mysqli -> affected_rows ) ;
}

?>

Example

Example 1 - Object-Oriented Style

Escape special characters in strings:

 <?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( $mysqli -> connect_errno ) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
  exit ( ) ;
}

// Escape special characters (if any)
$firstname = $mysqli -> real_escape_string ( $_POST [ 'firstname' ] ) ;
$lastname = $mysqli -> real_escape_string ( $_POST [ 'lastname' ] ) ;
$age = $mysqli -> real_escape_string ( $_POST [ 'age' ] ) ;

$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES (' $firstname ', ' $lastname ', ' $age ')" ;

if ( ! $mysqli -> query ( $sql ) ) {
  printf ( "%d Row inserted.\n" , $mysqli -> affected_rows ) ;
}

$mysqli -> close ( ) ;
?>

Example 2 - Procedural Style

Escape special characters in strings:

 <?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;

if ( mysqli_connect_errno ( ) ) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
  exit ( ) ;
}

// Escape special characters (if any)
$firstname = mysqli_real_escape_string ( $con , $_POST [ 'firstname' ] ) ;
$lastname = mysqli_real_escape_string ( $con , $_POST [ 'lastname' ] ) ;
$age = mysqli_real_escape_string ( $con , $_POST [ 'age' ] ) ;

$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES (' $firstname ', ' $lastname ', ' $age ')" ;

if ( ! mysqli_query ( $con , $sql ) ) {
  printf ( "%d Row inserted.\n" , mysqli_affected_rows ( $con ) ) ;
}

mysqli_close ( $con ) ;
?>
Similar Functions
Popular Articles