Real_escape_string

In this article, we will discuss the mysqli_real_escape_string() function in PHP, which is used to escape special characters in strings that will be used in SQL queries.

Introduction to the mysqli_real_escape_string() function

The mysqli_real_escape_string() function is a built-in function in PHP that is used to escape special characters in strings that will be used in SQL queries. This function is used to prevent SQL injection attacks, which occur when a malicious user inserts SQL code into an SQL statement that is executed by the database.

How to use the mysqli_real_escape_string() function

Using the mysqli_real_escape_string() function is straightforward. Here's an example:

<?php
$con = mysqli_connect('localhost', 'username', 'password', 'database');

if (!$con) {
    die('Could not connect: ' . mysqli_error());
}

$name = "John O'Reilly";
$name = mysqli_real_escape_string($con, $name);

$sql = "INSERT INTO customers (name) VALUES ('$name')";

if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}

echo '1 record added';

mysqli_close($con);
?>

In this example, we first establish a connection to a MySQL database using the mysqli_connect() function. We then define a string variable called $name, which contains a name that includes a single quote character. We use the mysqli_real_escape_string() function to escape the single quote character, which ensures that the SQL statement will be executed correctly. We then create an SQL statement that inserts the $name variable into a table called customers. We execute the SQL statement using the mysqli_query() function and output a success message using the echo statement.

Conclusion

In conclusion, the mysqli_real_escape_string() function is a vital tool for preventing SQL injection attacks in PHP. By using this function to escape special characters in strings that will be used in SQL queries, you can ensure that your code is secure and your data is protected.

Practice Your Knowledge

What does the PHP function mysql_real_escape_string function do?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?