Using mysqli_real_escape_string()

Using mysqli_real_escape_string() in MySQLi
When developing web applications that interact with databases, one of the most critical aspects of security is ensuring that user inputs are handled safely. SQL injection is a common attack vector where malicious users inject SQL queries into your application through user inputs.
mysqli_real_escape_string() is a function provided by the MySQLi extension in PHP to help protect against such attacks by escaping special characters in strings that are used in SQL queries. This article will explore the usage of mysqli_real_escape_string(), provide examples, and explain best practices for securing your database queries.

Understanding SQL Injection

SQL injection is a vulnerability that occurs when an attacker is able to manipulate the SQL queries executed by your application. This can lead to unauthorized access to your database, data leakage, or even data manipulation. For example, consider a login form where a user inputs their username and password. If these inputs are directly included in an SQL query without proper escaping, an attacker could input something like:
				
					' OR '1'='1

				
			

This input could alter the query to:

				
					SELECT * FROM users WHERE username='' OR '1'='1' AND password='';

				
			
This modified query might bypass authentication entirely, allowing unauthorized access.

What is mysqli_real_escape_string()?

mysqli_real_escape_string() is a PHP function that escapes special characters in a string to make it safe for use in SQL queries. It is specifically designed to handle user inputs and protect against SQL injection attacks. The function works by escaping characters such as single quotes, double quotes, backslashes, and NULL bytes, which could be used to manipulate SQL queries.

Function Syntax

The syntax for mysqli_real_escape_string() is:
				
					mysqli_real_escape_string(mysqli $link, string $escapestr): string

				
			
  • $link: The MySQLi connection link identifier.
  • $escapestr: The string to be escaped.

Using mysqli_real_escape_string() with Examples

Let’s explore how to use mysqli_real_escape_string() with some practical examples.

1. Basic Usage

First, establish a connection to the MySQL database:
				
					<?php
// Database configuration
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'test_db';

// Create a connection
$conn = new mysqli($host, $user, $password, $database);

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

				
			
Now, let’s use mysqli_real_escape_string() to safely handle user inputs:
				
					<?php
// Assume we get user input from a form
$user_input = $_POST['user_input'];

// Escape the user input
$safe_input = mysqli_real_escape_string($conn, $user_input);

// Use the escaped input in a query
$sql = "SELECT * FROM users WHERE username='$safe_input'";
$result = $conn->query($sql);

// Process the result
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "User: " . $row['username'] . "<br>";
    }
} else {
    echo "No results found.";
}
?>

				
			
In this example, mysqli_real_escape_string() is used to escape the user input before including it in the SQL query, preventing SQL injection.

2. Handling Multiple User Inputs

When dealing with multiple user inputs, it’s important to escape each one individually:
				
					<?php
// Assume we get multiple user inputs from a form
$username = $_POST['username'];
$password = $_POST['password'];

// Escape the user inputs
$safe_username = mysqli_real_escape_string($conn, $username);
$safe_password = mysqli_real_escape_string($conn, $password);

// Use the escaped inputs in a query
$sql = "INSERT INTO users (username, password) VALUES ('$safe_username', '$safe_password')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
?>

				
			
In this example, both the username and password are escaped to ensure they are safely included in the SQL query.

3. Escaping Strings for Dynamic Queries

When building dynamic queries, you can use mysqli_real_escape_string() to ensure that all parts of the query are safe:
				
					<?php
// Assume we get parameters for a search query
$search_term = $_POST['search_term'];
$sort_order = $_POST['sort_order'];

// Escape the parameters
$safe_search_term = mysqli_real_escape_string($conn, $search_term);
$safe_sort_order = mysqli_real_escape_string($conn, $sort_order);

// Construct the query
$sql = "SELECT * FROM products WHERE product_name LIKE '%$safe_search_term%' ORDER BY price $safe_sort_order";
$result = $conn->query($sql);

// Process the result
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "Product: " . $row['product_name'] . " - Price: " . $row['price'] . "<br>";
    }
} else {
    echo "No products found.";
}
?>

				
			
In this example, mysqli_real_escape_string() is used to escape both the search term and the sort order, ensuring that the dynamic parts of the query are safe.

4. Escaping User Input for Prepared Statements

Although mysqli_real_escape_string() helps protect against SQL injection, the preferred method for secure queries is to use prepared statements. Prepared statements provide a stronger level of protection against SQL injection:
				
					<?php
// Prepare a statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");

// Bind parameters
$stmt->bind_param("ss", $username, $password);

// Set parameters and execute
$username = $_POST['username'];
$password = $_POST['password'];
$stmt->execute();

// Get result
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "User: " . $row['username'] . "<br>";
    }
} else {
    echo "No results found.";
}

// Close statement
$stmt->close();
?>

				
			
In this example, the mysqli_prepare() and mysqli_stmt_bind_param() functions are used to prepare and execute a secure query, avoiding the need for manual escaping.

Best Practices for Using mysqli_real_escape_string()

  1. Always Escape User Inputs: Ensure that all user inputs are escaped before including them in SQL queries. This includes data received from forms, URL parameters, and other sources.
  2. Use Prepared Statements: While mysqli_real_escape_string() provides a level of protection, using prepared statements is recommended for a higher level of security. Prepared statements handle parameterized queries and provide better protection against SQL injection.
  3. Validate and Sanitize Inputs: In addition to escaping user inputs, validate and sanitize them to ensure they conform to expected formats. For example, use regex or built-in validation functions to check for valid email addresses or numeric values.
  4. Avoid Directly Including User Inputs in SQL Queries: Always use placeholders or prepared statements instead of directly including user inputs in SQL queries, even if you use mysqli_real_escape_string().
  5. Keep Your Software Up-to-Date: Regularly update PHP, MySQL, and any related libraries to ensure that you have the latest security patches and improvements.

Conclusion

mysqli_real_escape_string() is a valuable function for escaping special characters in strings used in SQL queries, helping to protect against SQL injection attacks. While it provides an essential layer of security, using prepared statements is the preferred method for executing secure queries. By combining these practices with input validation and sanitization, you can significantly enhance the security of your PHP and MySQL applications. Implementing robust error handling and security measures ensures that your web applications remain resilient and trustworthy, protecting both your data and your users from potential threats.
Scroll to Top