PHP mysqli_real_escape_string() Function
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($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"CREATE TABLE myPersons LIKE Persons");
$newpers="Da'Silva"
// This query will fail, cause we did not
escape $newpers
mysqli_query($con,"INSERT into myPersons (Lastname)
VALUES ('$newpers')");
$newpers=mysqli_real_escape_string($con,$newpers);
// This query will
work, cause we escaped $newpers
mysqli_query($con,"INSERT into myPersons
(Lastname) VALUES ('$newpers')");
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
Thank You For Helping Us!
Your message has been sent to W3Schools.
Close [X]