Current Location: Home> Latest Articles> How to Effectively Prevent SQL Injection Attacks Using real_escape_string in PHP

How to Effectively Prevent SQL Injection Attacks Using real_escape_string in PHP

gitbox 2025-06-10

What is real_escape_string?

real_escape_string is a method in the mysqli extension that primarily escapes special characters in strings to prevent malicious SQL code execution. It automatically adds a backslash (\) before dangerous characters, neutralizing their special meaning in SQL syntax.

When should you use real_escape_string?

Whenever user input is directly concatenated into an SQL statement, you need to escape the input. Otherwise, attackers can craft malicious inputs that alter the logic of your database operations.

How to properly use real_escape_string?

Here is a simple example demonstrating how to safely handle user input with real_escape_string:

<?php // Create a mysqli connection $conn = new mysqli('gitbox.net', 'username', 'password', 'database');

// Check if the connection was successful
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Assume the user submitted a username via a form
$user_input = $_POST['username'];

// Use real_escape_string to escape the user input
$safe_input = $conn->real_escape_string($user_input);

// Construct the SQL query
$sql = "SELECT * FROM users WHERE username = '$safe_input'";

// Execute the query
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// Process the query results
while ($row = $result->fetch_assoc()) {
echo "User ID: " . $row["id"] . " - Username: " . $row["username"] . "
";
}
} else {
echo "No matching user found.";
}

$conn->close();
?>

Why does real_escape_string prevent SQL injection?

real_escape_string identifies characters in strings that could be misinterpreted by the SQL engine—such as single quotes ('), double quotes ("), and backslashes (\)—and prepends a backslash to them. This removes their special meaning in SQL syntax, preventing malicious code execution.

Important considerations

  1. The connection must be established: real_escape_string depends on an active database connection and should not be called before the connection is made.

  2. Scope of use: This function only escapes strings and cannot replace more secure prepared statements.

  3. Prepared statements are recommended: Although real_escape_string is effective, it is better to use mysqli or PDO prepared statements for SQL queries to improve security and maintainability.

  • Related Tags:

    SQL