THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP mysqli_real_escape_string() Function

PHP MySQLi Reference PHP MySQLi Reference

Example

Escape special characters in a string:

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

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

// escape variables for security
$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)) {
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>

Definition and Usage

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.


Syntax

mysqli_real_escape_string(connection,escapestring);

Parameter Description
connection Required. Specifies the MySQL connection to use
escapestring Required. The string to be escaped. Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.

Technical Details

Return Value: Returns the escaped string
PHP Version: 5+

PHP MySQLi Reference PHP MySQLi Reference