Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP | mysqli_real_escape_string() Function

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");
        
// 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




<?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_escape', '$lastname_escape')";
 
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. 

 

RELATED ARTICLES

Most Popular

Recent Comments