PHP | mysqli_real_escape_string() Function
The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations.
When simple strings are used, there are chances that special characters like backslashes and apostrophes are included in them (especially when they are getting data directly from a form where such data is entered). These are considered to be part of the query string and interfere with its normal functioning.
php
<?php
$connection = mysqli_connect(
"localhost" , "root" , "" , "Persons" );
if (mysqli_connect_errno()) {
echo "Database connection failed." ;
}
$firstname = "Robert'O" ;
$lastname = "O'Connell" ;
$sql ="INSERT INTO Persons (FirstName, LastName)
VALUES ( '$firstname' , '$lastname' )";
if (mysqli_query( $connection , $sql )) {
printf( "%d row inserted.\n" ,
$mysqli ->affected_rows);
}
else {
printf( "An error occurred!" );
}
?>
|
In the above code, the query fails because the apostrophes are considered as part of the query when it is executed using mysqli_query(). The solution is to use mysqli_real_escape_string() before using the strings in the query.
php
<?php
$connection = mysqli_connect(
"localhost" , "root" , "" , "Persons" );
if (mysqli_connect_errno()) {
echo "Database connection failed." ;
}
$firstname = "Robert'O" ;
$lastname = "O'Connell" ;
$lastname_escape = mysqli_real_escape_string(
$connection , $lastname );
$firstname_escape = mysqli_real_escape_string(
$connection , $firstname );
$sql ="INSERT INTO Persons (FirstName, LastName)
VALUES ( '$firstname_escape' , '$lastname_escape' )";
if (mysqli_query( $connection , $sql )) {
printf( "%d row inserted.\n" , $mysqli ->affected_rows);
}
?>
|
Output:
1 row inserted.
Last Updated :
16 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...