Escape special characters in a string in PHP
Description
The following code shows how to escape special characters in a string.
Example
//from w w w . j ava 2 s . co m
<?php
$con=mysqli_connect("localhost","root","","test");
// 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['name']);
$sql="INSERT INTO employee(Name)VALUES ('$firstname')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
The code above generates the following result.