Skip to content
Related Articles

Related Articles

PHP | mysqli_real_escape_string() Function
  • Difficulty Level : Easy
  • Last Updated : 27 Apr, 2020

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
  
$connection = mysqli_connect(
    "localhost", "root", "", "Persons"); 
         
// Check connection 
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)) {
      
    // Print the number of rows inserted in
    // the table, if insertion is successful
    printf("%d row inserted.\n",
            $mysqli->affected_rows);
}
else {
      
    // Query fails because the apostrophe in 
    // the string interferes with the query
    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
   
$connection = mysqli_connect(
        "localhost", "root", "", "Persons"); 
  
// Check connection 
if (mysqli_connect_errno()) { 
    echo "Database connection failed."
       
$firstname = "Robert'O";
$lastname = "O'Connell";
   
// Remove the special characters from the
// string using mysqli_real_escape_string
   
$lastname_escape = mysqli_real_escape_string(
                    $connection, $lastname);
                      
$firstname_escape = mysqli_real_escape_string(
                    $connection, $firstname);
   
$sql="INSERT INTO Persons (FirstName, LastName)
            VALUES ('$firstname', '$lastname')";
  
if (mysqli_query($connection, $sql)) {
      
    // Print the number of rows inserted in
    // the table, if insertion is successful
    printf("%d row inserted.\n", $mysqli->affected_rows);
}
   
?>

Output:

1 row inserted. 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :