• Home
  • Real escape string and PDO

Real escape string and PDO

The mysqli_real_escape_string() function is a security function in PHP that is used to escape special characters in a string for use in an SQL query. It is particularly useful for preventing SQL injection attacks, as it allows you to safely include user-provided input in an SQL query without worrying about special characters being misinterpreted.

The mysqli_real_escape_string() function takes two arguments: the MySQL connection and the string to be escaped. It returns the escaped string, which can then be used in an SQL query.

Here is an example of using mysqli_real_escape_string() to escape a string for use in an SQL query:

$link = mysqli_connect("localhost", "username", "password", "database");
$text = "O'Reilly";
$escaped_text = mysqli_real_escape_string($link, $text);
$query = "INSERT INTO table (column) VALUES ('$escaped_text')";
mysqli_query($link, $query);

In this example, the mysqli_real_escape_string() function escapes the apostrophe in the $text string, so that it can be safely included in the SQL query. The resulting query would be equivalent to INSERT INTO table (column) VALUES ('O\'Reilly'), which is a valid SQL query.

PHP Data Objects (PDO) is a database abstraction library in PHP that provides a uniform interface for accessing different types of databases. PDO supports prepared statements and parameterized queries, which allow you to separate the SQL code from the data being provided by the user.

Here is an example of using PDO to insert data into a MySQL database:

$link = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$text = "O'Reilly";
$stmt = $link->prepare("INSERT INTO table (column) VALUES (?)");
$stmt->bindParam(1, $text);
$stmt->execute();

In this example, the prepare() method creates a prepared statement with a placeholder for the data being inserted. The bindParam() method binds the value of the $text variable to the placeholder, and the execute() method executes the prepared statement. This allows you to safely insert the $text string into the database without worrying about special characters being misinterpreted.

Using mysqli_real_escape_string() or PDO can help to prevent SQL injection attacks and ensure that your PHP code is secure and reliable. It is important to properly handle user-provided input to avoid security vulnerabilities and ensure the integrity of your data.